简体   繁体   中英

How to solve Django ManyToMany relationship with 2 levels

I have a structure like this in 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() ?

You can obtain these through a filter, like:

Hashtag.objects.filter()

so if you want to add that as a property in your Profile class for example, you can implement this as:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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