简体   繁体   English

如何解决 2 个级别的 Django ManyToMany 关系

[英]How to solve Django ManyToMany relationship with 2 levels

I have a structure like this in Django 1.11:我在 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()

Now this creates intermediate table post_hashtag, but how can I access all hashtags using profile.hashtags.all() ?现在这会创建中间表 post_hashtag,但是如何使用profile.hashtags.all()访问所有主题标签?

You can obtain these through a filter, like:您可以通过过滤器获得这些,例如:

Hashtag.objects.filter(post__profile=my_profile)

so if you want to add that as a property in your Profile class for example, you can implement this as:因此,例如,如果您想将其添加为Profile类中的属性,则可以将其实现为:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM