python - 如何在 django View 中使用 unique_together 方法

标签 python django python-2.7 django-models django-views

class Model1(models.Model):
     username = models.CharField(max_length=100,null=False,blank=False,unique=True)
     password = models.CharField(max_length=100,null=False,blank=False)

class Model2(models.Model):
     name = models.ForeignKey(Model1, null=True)
     unique_str = models.CharField(max_length=50,null=False,blank=False,unique=True)
     city = models.CharField(max_length=100,null=False,blank=False)
     class Meta:
           unique_together = (('name', 'unique_str'),)

我已经通过 django-admin 页面在 Model1 中填写了 3 个示例用户名密码

在我看来,我得到的这个列表是

userlist = Model1.objects.all()
#print userlist[0].username, userlist[0].password

for user in userlist:
     #here I want to get or create model2 object by uniqueness defined in meta class.
     #I mean unique_str can belong to multiple user so I'm making name and str together as a unique key but I dont know how to use it here with get_or_create method.
     #right now (without using unique_together) I'm doing this (but I dont know if this by default include unique_together functionality )
     a,b = Model2.objects.get_or_create(unique_str='f3h6y67')
     a.name = user
     a.city = "acity"
     a.save()

最佳答案

我认为您的意思是,您的逻辑键是 nameunique_together 的组合,并且您可以使用它作为调用的基础get_or_create()

首先,了解unique_together 创建数据库约束。无法使用它,并且 Django 不会对这些信息执行任何特殊操作。

此外,目前 Django 无法使用复合自然主键,因此默认情况下您的模型将具有自动递增整数主键。但您仍然可以使用 nameunique_str 作为键。

看看你的代码,你似乎想这样做:

a, _ = Model2.objects.get_or_create(unique_str='f3h6y67', 
                                    name=user.username)
a.city = 'acity'
a.save()

在 Django 1.7 上,您可以使用 update_or_create():

a, _ = Model2.objects.update_or_create(unique_str='f3h6y67', 
                                       name=user.username,
                                       defaults={'city': 'acity'})

无论哪种情况,关键点是 _or_create 的关键字参数用于查找对象,而 defaults 用于在这种情况下提供附加数据创建或更新的。请参阅the documentation .

总而言之,要“使用”unique_together 约束,只要您想要唯一地指定一个实例,您只需将这两个字段一起使用即可。

关于python - 如何在 django View 中使用 unique_together 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23770190/

相关文章:

python - 如何为 Python Swigged C++ 对象创建和分配回调函数

python - 我将工作代码复制并粘贴到我的 IDE 中——现在 Python 抛出了大量错误

python - 链接到 Django 1.3 中的静态文件的问题

python - 丢弃返回的变量

python - 浮点十六进制字符串变回 float

python - Azure 机器学习工作室 : OSError: Cannot save file into a non-existent directory

python - 将RGB白色设置为透明?

python - 将 excel 的值作为 python 字典检索

python - 如何配置 Django、PostgreSQL、Apache 和 Python?

python - 反转数据框中的行值