Django ManyToMany字段:'tuple'对象没有'user'属性
我遇到了一个小问题,关于Django的...
这是我的模型:
class Mymodel(models.Model):
[...]
user = models.ManyToManyField(User)
这是我尝试创建新用户的代码:
mymodel = Mymodel.objects.get_or_create(date=date, day=day, time=time) # This one gives a solid Mymodel object i can play with
mymodel.user.add(user) # User is a instance of the Django User System
但是在执行的时候,出现了'tuple'对象没有'user'这个属性的错误。
我是不是不小心把它变成了一个元组?
1 个回答
12
get_or_create
这个函数会返回一个包含两个部分的组合,分别是 (对象, 是否新建)。如果你只想要模型对象,可以使用:
mymodel, _ = Mymodel.objects.get_or_create(date=date, day=day, time=time)
或者
mymodel = Mymodel.objects.get_or_create(date=date, day=day, time=time)[0]