我必须遵循 Django 中模型的代码:
class User(models.Model):
username = models.CharField(max_length=50, unique=True)
password = models.CharField(max_length=15)
class Follows(models.Model):
user = models.ManyToManyField(User, related_name = 'Isread+')
follower = models.ManyToManyField(User, related_name = 'Reads+')
当我尝试这样做时,我收到错误:
>>> from twitter.models import *
>>> u1 = User.objects.all()[0]
>>> u2 = User.objects.all()[1]
>>> Follows.objects.create(user = u1, follower = u2)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:Python33libsite-packagesdjangodbmodelsmanager.py", line 149, in create
return self.get_query_set().create(**kwargs)
File "C:Python33libsite-packagesdjangodbmodelsquery.py", line 414, in create
obj = self.model(**kwargs)
File "C:Python33libsite-packagesdjangodbmodelsbase.py", line 415, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'follower' is an invalid keyword argument for this function
有谁知道为什么会这样?提前感谢。
由于您有一个 ManyToManyField,您首先需要创建 Follows
对象(保存它),以便它具有主键,以便多对多关系正常工作。此外,您需要使用多对多管理器将项目添加到关系中。
简而言之,您需要这样做:
f = Followers()
f.save()
f.user.add(u1)
f.follower.add(u2)
f.save()