【问题标题】:How to solve Django ManyToMany relationship with 2 levels如何解决 2 个级别的 Django 多对多关系
【发布时间】:2021-01-15 14:17:33
【问题描述】:

我在 Django 1.11 中有这样的结构:

class Profile(models.Model):
    username = models.CharField()

class Post(models.Model):
    profile = models.ForeignKey(Profile)
    hashtag = models.ManyToManyField(Hashtag)

class Hashtag(models.Model):
    name = models.CharField()

现在这会创建中间表 post_hashtag,但是如何使用 profile.hashtags.all() 访问所有主题标签?

【问题讨论】:

  • Hashtag.objects.filter(post__profile=my_profile)

标签: python python-3.x django django-models manytomanyfield


【解决方案1】:

您可以通过过滤器获得这些,例如:

Hashtag.objects.filter(<b>post__profile=<i>my_profile</i></b>)

因此,例如,如果您想将其作为属性添加到您的 Profile 类中,您可以将其实现为:

class Profile(models.Model):
    username = models.CharField()

    @property
    def hashtags(self):
        return Hashtag.objects.filter(post__profile=self)

【讨论】:

  • 感谢您的回复,这是我已经实现的一种方法(我发现唯一可行的方法),我想知道是否有一种方法可以通过调用 post. hashtags.all() 使用一些自定义管理器或任何其他棘手的方式?只是我要检索的所有其他对象都使用 all() 方法,而这个很突出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
  • 2019-03-31
  • 2013-03-05
  • 1970-01-01
相关资源
最近更新 更多