关注像Django中的twitter这样的用户,管理用户界面

2024-03-29 05:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我创建的类,用于使用户遵循模型。但是,它似乎不工作的权利。当我在admin中创建follow时,它会不断打开一个新的adduserfollowing窗口来填充follow字段。所以,我无法创造它。你知道吗

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.

密码怎么了?你知道吗


Tags: or用户模型getobjectsmodelscreateusername
1条回答
网友
1楼 · 发布于 2024-03-29 05:20:18

在设置follows属性之前,是否创建了与用户关联的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/

相关问题 更多 >