关注用户喜欢 Django 中的 twitter,Admin UI



这是我创建的类,用于使用户遵循模型。但是,它似乎无法正常工作。当我在管理员中创建关注时,它会不断打开一个新的添加 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) 

外壳退出并给出错误:

fest.models.DoesNotExist: User has no userfollowing.

代码有什么问题?

您是否在设置跟随属性之前创建了与用户关联的 UserFollow 对象?

即:

假设您有模型:

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

您将在外壳中键入:

>>> 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/

最新更新