gtfx
gtfx

Reputation: 313

Django fetch all relations

I have an app with a similar structure as this snippet

class Blog(models.Model):
    name = models.CharField(max_length=25)

class Category(models.Model):
    name = models.CharField(max_length=25)
    blog = models.ForeignKey(Blog)

class Entry(models.Model):
    title = models.CharField(max_length=25)
    category = models.ForeignKey(Category)

What is the most generic way, that i will be able to use in other apps to fetch all blogs with their category and entries?

I thought about creating a manager for the Blog model, that can fetch all the Categories for that blog, but it's hardcoding the model names

 class BlogManager(models.Manager):
     def categories(self):
         return Category.objects.filter(blog=self)

Any suggestions?

Upvotes: 0

Views: 2503

Answers (2)

garmoncheg
garmoncheg

Reputation: 906

Why not use a standard way? Filter using Blog's PK with FK relation.

Category.objects.filter(blog__pk=self.pk)

Upvotes: 0

Zain Khan
Zain Khan

Reputation: 3793

What you want is a Select Related. It returns a QuerySet that will automatically "follow" foreign-key relationships, selecting that additional related-object data when it executes its query. Your query for Blogs would look something like:

Blog.objects.select_related().filter( something )

or

Blog.objects.select_related().get( something )

Upvotes: 3

Related Questions