[英]How to use unique_together method in 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'),)
I've already filled 3 sample username-password in Model1 through django-admin page 我已经通过django-admin页面在Model1中填写了3个示例用户名密码
In my views I'm getting this list as 在我看来,我得到这个清单
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()
What I think you're saying is that your logical key is a combination of name
and unique_together
, and that you what to use that as the basis for calls to get_or_create()
. 我认为您的意思是您的逻辑键是
name
和unique_together
的组合,并且您将使用它作为调用get_or_create()
的基础。
First, understand the unique_together
creates a database constraint. 首先,了解
unique_together
创建数据库约束。 There's no way to use it, and Django doesn't do anything special with this information. 没有办法使用它,并且Django对此信息没有做任何特殊的事情。
Also, at this time Django cannot use composite natural primary keys, so your models by default will have an auto-incrementing integer primary key. 另外,此时Django无法使用复合自然主键,因此默认情况下,您的模型将具有自动递增的整数主键。 But you can still use
name
and unique_str
as a key. 但是您仍然可以使用
name
和unique_str
作为键。
Looking at your code, it seems you want to do this: 查看您的代码,看来您想这样做:
a, _ = Model2.objects.get_or_create(unique_str='f3h6y67',
name=user.username)
a.city = 'acity'
a.save()
On Django 1.7 you can use update_or_create()
: 在Django 1.7上,您可以使用
update_or_create()
:
a, _ = Model2.objects.update_or_create(unique_str='f3h6y67',
name=user.username,
defaults={'city': 'acity'})
In either case, the key point is that the keyword arguments to _or_create
are used for looking up the object, and defaults
is used to provide additional data in the case of a create or update. 在这两种情况下,关键点都是
_or_create
的关键字参数用于查找对象,而在创建或更新的情况下, defaults
用于提供其他数据。 See the documentation . 请参阅文档 。
In sum, to "use" the unique_together
constraint you simply use the two fields together whenever you want to uniquely specify an instance. 总而言之,要“使用”
unique_together
约束,只要想唯一指定一个实例,就可以将两个字段一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.