【问题标题】:django queryset filter foreignkeydjango queryset过滤外键
【发布时间】:2018-01-05 17:35:52
【问题描述】:

我在尝试对我的模型使用查询集过滤器时遇到问题。 它是组中帖子的控件。

这是我的代码:

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)

我正在尝试从标题为“title”的组中获取所有帖子:

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

我的模型可能是正确的,我是新手。 有什么帮助吗?

【问题讨论】:

  • 为什么有Control 模型? Post 是否可以在一个组中发布而不在另一个组中发布?
  • 是的,我可能有针对特定组的不同帖子。

标签: django foreign-keys django-queryset


【解决方案1】:

首先,您应该在Group (docs) 上添加一个ManyToManyField

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

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

其他两个模型保持不变,但现在您可以轻松抓取群组的帖子:

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

【讨论】:

  • 我收到此错误:文件“”,第 678 行,在 exec_module 文件“”,第 205 行,在 _call_with_frames_removed 文件“/home/renan/ django/social-posts/src/control/models.py”,第 21 行,在 类 Control(models.Model) 中:文件“/home/renan/django/social-posts/src/control/models.py ",第 24 行,在 Control group = models.ForeignKey(Group, on_delete=models.CASCADE) NameError: name 'Group' is not defined
  • 假设您将 Group 移到 Control 之下?将Group 放在引号中:group = models.ForeignKey('Group', on_delete=models.CASCADE)
  • 好吧,它也没有用。这是我的代码(没有多对多关系):bitbucket.org/renanbs/social-posts.
  • 同样的错误还是别的什么?您是否查看了我在答案中链接到的文档?没有看到代码+错误很难提供帮助。
  • 这是错误:.resolve_through_model at 0x7ff5f28f81e0> 包含对 groups.control 的惰性引用,但应用程序“组”不提供模型“控制”。 groups.Group.posts:(fields.E300)字段定义与模型“Post”的关系,该模型要么未安装,要么是抽象的。 groups.Group.posts: (fields.E307) 字段 groups.Group.posts 被声明为对“groups.post”的惰性引用,但应用程序“groups”不提供模型“post”。 groups.Group.posts: (fields.E331) 字段通过模型'Control'指定多对多关系,尚未安装。
【解决方案2】:

可能是拼写错误?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-11
    • 2011-07-23
    • 2014-07-13
    • 1970-01-01
    • 2020-09-07
    • 2012-01-23
    • 1970-01-01
    • 2013-09-08
    相关资源
    最近更新 更多