【问题标题】:What is the best way to store array of characters in django model?在 django 模型中存储字符数组的最佳方法是什么?
【发布时间】:2014-12-17 18:06:27
【问题描述】:

我有一个 MAC 地址数组。如何将它们存储在 Django 1.7 模型中?我的代码是:

MAC=models.CharField(max_length = 20,null=True,blank=True)

我必须为单个用户存储不同的 MAC 地址

【问题讨论】:

    标签: python django django-models django-1.7


    【解决方案1】:

    这取决于您的使用情况。我猜你想将可变数量的 MAC 地址分配给其他模型,每个 MAC 地址只能使用一次。

    class Parent(models.Model):
        pass
    
    class MacAddress(models.Model):
        parent = models.ForeignKey(Parent, related_name='mac_addresses')
        address = models.CharField(max_length = 20,null=True,blank=True, unique=True)
    

    因此,对于数组中的每个地址,您将创建一个 MacAddress 的新实例

    【讨论】:

    • 我必须为单个用户存储不同的 MAC 地址
    • 我如何为数组中的每个地址创建一个新的 MacAddress 实例?
    • 是的。 MacAddress 只是我示例中的另一个模型。您可以使用bulk_create 或带有MacAddress.objects.create 的for 循环。
    【解决方案2】:

    最好的方法是使用多对多字段。

    我的模型.py

    class MacAddress(models.Model):
        address = models.CharField(max_length = 20,null=True,blank=True)
        def __unicode__(self):
            return self.address
    
    class UserProfile(models.Model):
        user = models.OneToOneField(User,primary_key=True,db_index=True)
        MAC=models.ManyToManyField(MacAddress)
        def __unicode__(self):
            return self.user.username
    

    views.py

    mac = get_mac()
                mac = (hex(mac))
                MacAdd=MacAddress()
                MacAdd.address=mac
                MacAdd.save()
                profile.save()
                profile.MAC.add(MacAdd)
                profile.save()
    

    【讨论】:

      猜你喜欢
      • 2013-10-08
      • 2016-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 2010-11-09
      • 2017-03-14
      • 2020-04-08
      相关资源
      最近更新 更多