开发者

Django QuerySet join across four tables, including ManyToMany?

开发者 https://www.devze.com 2023-02-24 03:41 出处:网络
Given the following models, my goal is to create a QuerySet that pulls all available Tag objects for a given PostCategory id. I know how to write this in SQL but can\'t figure out how to do it using t

Given the following models, my goal is to create a QuerySet that pulls all available Tag objects for a given PostCategory id. I know how to write this in SQL but can't figure out how to do it using the Django ORM. I believe I'm following best practices by defining the relationships on the Post object, and not the Tag, but QuerySet syntax pattern seems like it would expect me to start with Tag.objects.filter() but I don't see how.

class Tag(models.Model):
    name = models.CharField(max_length=255)

class PostCategory(models.Model):
    name = models.CharField(max_length=100)    

class Post(models.Model):
    body_text = models.TextField()
    pub_date = models.DateTimeField()
    mod_date = models.DateTimeField(auto_now=True)
    title = models.CharField(max_length=255)
    subtitle = models.CharField(max_length=255) 
    is_featured = models.BooleanField()
    image = models.ImageField(upload_to='post_images')
    tags = models.ManyToManyFiel开发者_StackOverflow中文版d(Tag, null=True, blank=True)
    user = models.ForeignKey(User)
    category = models.ForeignKey(PostCategory)


tags = Tag.objects.filter(post__category_id=postcategory_id).distinct()
0

精彩评论

暂无评论...
验证码 换一张
取 消