按内容为models的字段筛选模型.ForeignKey(User)

时间:2022-02-18 18:05:54

I have a

我有一个

class Posts(models.Model):
    created_by = models.ForeignKey(User)
    post = models.CharField(max_length=150)
    active = models.NullBooleanField()
    def __unicode__(self):
        return self.post

and now i want to filter my class Posts by created_by=testuser. For that i do

现在我想通过created_by = testuser过滤我的类帖子。为此我做

p = Posts.objects.filter(created_by=poster, active=True)

whereby var(poster) comes from the requested url(r'^(?P<poster>\w+)/$', views.Posts),

var(海报)来自请求的网址(r'^(?P \ w +)/ $',views.Posts),

If i execute it by going to my-domain.tld/testuser i get a ValueError: invalid literal for int() with base 10: 'testuser'

如果我通过转到my-domain.tld / testuser来执行它,我会得到一个ValueError:int()的无效文字,基数为10:'testuser'

If i try to filter in manage.py shell i get the error NameError: name 'testuser' is not defined if i try to filter by the command p = Posts.objects.filter(created_by=testuser).

如果我尝试在manage.py shell中进行过滤,我会收到错误NameError:如果我尝试使用命令p = Posts.objects.filter(created_by = testuser)进行过滤,则不会定义名称'testuser'。

How is it done right to filter my field created_by that content is models.ForeignKey(User). Is there a solution anyway or should i create additional a CharField with creator (poster) as content?

如何正确过滤我的字段created_by内容是models.ForeignKey(用户)。无论如何还是有解决方案,还是应该创建额外的CharField作为内容创作者(海报)?

1 个解决方案

#1


1  

p = Posts.objects.filter(created_by__username=poster, active=True)

p = Posts.objects.filter(created_by__username = poster,active = True)

poster is just an name (str), you can span relationships and query by user.username using __

poster只是一个名称(str),您可以使用__跨越user.username的关系和查询

or you could fetch a user object first by poster

或者您可以先通过海报获取用户对象

user = Users.objects.get(username=poster)
p = Posts.objects.filter(created_by=user, active=True)

User model documentation can be found on site: https://docs.djangoproject.com/en/dev/topics/auth/#users

用户模型文档可在现场找到:https://docs.djangoproject.com/en/dev/topics/auth/#users

#1


1  

p = Posts.objects.filter(created_by__username=poster, active=True)

p = Posts.objects.filter(created_by__username = poster,active = True)

poster is just an name (str), you can span relationships and query by user.username using __

poster只是一个名称(str),您可以使用__跨越user.username的关系和查询

or you could fetch a user object first by poster

或者您可以先通过海报获取用户对象

user = Users.objects.get(username=poster)
p = Posts.objects.filter(created_by=user, active=True)

User model documentation can be found on site: https://docs.djangoproject.com/en/dev/topics/auth/#users

用户模型文档可在现场找到:https://docs.djangoproject.com/en/dev/topics/auth/#users