Django ManyToMany FIeld:'tuple'对象没有属性'user'

时间:2011-10-28 15:00:23

标签: python django django-models

有一点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 个答案:

答案 0 :(得分:9)

get_or_create返回由(object,created)组成的元组。要获得该模型,请使用:

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]