这是我创建的用于使用户遵循模型的类。但是,它似乎不正常。当我在管理员中创建一个关注者时,它会一直打开一个新的添加UserFollwing窗口来填充“关注”字段。所以,我无法创建它。
class UserFollowing(models.Model):
user = models.OneToOneField(User)
follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False)
另外,如果我使用以下命令在shell中创建它:
tim, c = User.objects.get_or_create(username='tim')
chris, c = User.objects.get_or_create(username='chris')
tim.userfollowing.follows.add(chris.userfollowing)
shell退出给出错误:
fest.models.DoesNotExist: User has no userfollowing.
代码有什么问题?
答案 0 :(得分:0)
在设置follow属性之前,您是否创建了一个与用户关联的UserFollowing对象?
即:
假设你有模特:
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
# On Python 3: def __str__(self):
def __unicode__(self):
return u"%s the place" % self.name
class Restaurant(models.Model):
place = models.OneToOneField(Place, primary_key=True)
serves_hot_dogs = models.BooleanField()
serves_pizza = models.BooleanField()
# On Python 3: def __str__(self):
def __unicode__(self):
return u"%s the restaurant" % self.place.name
您可以输入shell:
>>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
>>> p1.save()
>>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
>>> r.save()
>>> # accessing the restaurant as a property of the place
>>> p1.restaurant
<Restaurant: Demon Dogs the restaurant>
有关详细信息,请参阅https://docs.djangoproject.com/en/dev/topics/db/examples/one_to_one/