django queryset filter foreignkey

喜你入骨 提交于 2019-12-13 03:56:15

问题


I'm having problems trying to use the queryset filter with my models. It is a control for posts in groups.

This is my code:

class Post(models.Model):
    title = models.CharField(max_length=120)
    content = models.TextField()


class Group(models.Model):
    title = models.CharField(max_length=200)
    url = models.URLField(unique=True)


class Control(models.Model):
    published = models.DateField(auto_now=False, auto_now_add=False)

    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)

I'm trying to get all posts from a group with the title "title":

queryset_list = Control.objects.filter(group__control="title")

My models might nit be right, I'm new to this. Any help?


回答1:


Maybe it typo error?

queryset_list = Control.objects.filter(group__title="title")
#                                             ^^^^^^
posts_title = queryset_list.values('post__title')



回答2:


First, you should add a ManyToManyField on Group (docs):

class Group(models.Model):
    title = models.CharField(max_length=200)
    url = models.URLField(unique=True)

    posts = models.ManyToManyField('Post', through='Control')

The other two models remain the same, but now you can easily grab posts for a Group:

posts = Group.objects.get(title='some title').posts.all()


来源:https://stackoverflow.com/questions/45393989/django-queryset-filter-foreignkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!