Home > Enterprise >  How to get only the referenced objects in Django?
How to get only the referenced objects in Django?

Time:08-26

I have two models:

class ArticleCategory(models.Model):
    Category_name = models.CharField(max_length=50, null=False, blank=False)

    def __str__(self):
        return self.Category_name

class Article(models.Model):
    Title = models.CharField(max_length=100, blank=False, null=False)
    Content = tinymce_models.HTMLField(null=False, blank=False)
    Category = models.ManyToManyField(ArticleCategory,blank=False)

Assuming that the user will create some categories without necessarily linking them to any article, how do I get all the ArticleCategory objects that at least have one Article object linked to them?

CodePudding user response:

Use reverse relation in filtering with isnull lookup:

ArticleCategory.objects.filter(articles__isnull=False).distinct()

But first, add related_name to the proper field:

Category = models.ManyToManyField(ArticleCategory, blank=False, related_name="articles")

By the way, don't name fields in CamelCase style, save it for class names.

  • Related