Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8720469
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T07:02:52+00:00 2026-06-13T07:02:52+00:00

Suppose I have a model Box with a GenericForeignKey that points to either an

  • 0

Suppose I have a model Box with a GenericForeignKey that points to either an Apple instance or a Chocolate instance. Apple and Chocolate, in turn, have ForeignKeys to Farm and Factory, respectively. I want to display a list of Boxes, for which I need to access Farm and Factory. How do I do this in as few DB queries as possible?

Minimal illustrative example:

class Farm(Model):
    ...

class Apple(Model):
    farm = ForeignKey(Farm)
    ...

class Factory(Model):
    ...

class Chocolate(Model):
    factory = ForeignKey(Factory)
    ...

class Box(Model)
    content_type = ForeignKey(ContentType)
    object_id = PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    ...

    def __unicode__(self):
        if self.content_type == ContentType.objects.get_for_model(Apple):
            apple = self.content_object
            return "Apple {} from Farm {}".format(apple, apple.farm)
        elif self.content_type == ContentType.objects.get_for_model(Chocolate):
            chocolate = self.content_object
            return "Chocolate {} from Factory {}".format(chocolate, chocolate.factory)

Here are a few things I tried. In all these examples, N is the number of Boxes. The query count assumes that the ContentTypes for Apple and Chocolate have already been cached, so the get_for_model() calls do not hit the DB.

1) Naive:

print [box for box in Box.objects.all()]

This does 1 (fetch Boxes) + N (fetch Apple or Chocolate for each Box) + N (fetch Farm for each Apple and Factory for each Chocolate) queries.

2) select_related doesn’t help here, because Box.content_object is a GenericForeignKey.

3) As of django 1.4, prefetch_related can fetch GenericForeignKeys.

print [box for box in Box.objects.prefetch_related('content_object').all()]

This does 1 (fetch Boxes) + 2 (fetch Apples and Chocolates for all Boxes) + N (fetch Farm for each Apple and Factory for each Chocolate) queries.

4) Apparently prefetch_related isn’t smart enough to follow ForeignKeys of GenericForeignKeys. If I try:

print [box for box in Box.objects.prefetch_related(
'content_object__farm',
'content_object__factory').all()]

it rightfully complains that Chocolate objects don’t have a farm field, and vice versa.

5) I could do:

apple_ctype = ContentType.objects.get_for_model(Apple)
chocolate_ctype = ContentType.objects.get_for_model(Chocolate)
boxes_with_apples = Box.objects.filter(content_type=apple_ctype).prefetch_related('content_object__farm')
boxes_with_chocolates = Box.objects.filter(content_type=chocolate_ctype).prefetch_related('content_object__factory')

This does 1 (fetch Boxes) + 2 (fetch Apples and Chocolates for all Boxes) + 2 (fetch Farms for all Apples and Factories for all Chocolates) queries. The downside is that I have to merge and sort the two querysets (boxes_with_apples, boxes_with_chocolates) manually. In my real application, I’m displaying these Boxes in a paginated ModelAdmin. It’s not obvious how to integrate this solution there. Maybe I could write a custom Paginator to do this caching transparently?

6) I could cobble together something based on this that also does O(1) queries. But I’d rather not mess with internals (_content_object_cache) if I can avoid it.

In summary: Printing a Box requires access to the ForeignKeys of a GenericForeignKey. How can I print N Boxes in O(1) queries? Is (5) the best I can do, or is there a simpler solution?

Bonus points: How would you refactor this DB schema to make such queries easier?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T07:02:53+00:00Added an answer on June 13, 2026 at 7:02 am

    You can manually implement something like prefetch_selected and use Django’s select_related method, that will make join in database query.

    apple_ctype = ContentType.objects.get_for_model(Apple)
    chocolate_ctype = ContentType.objects.get_for_model(Chocolate)
    boxes = Box.objects.all()
    content_objects = {}
    # apples
    content_objects[apple_ctype.id] = Apple.objects.select_related(
        'farm').in_bulk(
            [b.object_id for b in boxes if b.content_type == apple_ctype]
        )
    # chocolates
    content_objects[chocolate_ctype.id] = Chocolate.objects.select_related(
        'factory').in_bulk(
            [b.object_id for b in boxes if b.content_type == chocolate_ctype]
        )
    

    This should make only 3 queries (get_for_model queries are omitted). The in_bulk method returns a dict in the format {id: model}. So to get your content_object you need a code like:

    content_obj = content_objects[box.content_type_id][box.object_id]
    

    However I’m not sure if this code will be quicker than your O(5) solution as it requires additional iteration over boxes queryset and it also generates a query with a WHERE id IN (...) statement.

    But if you sort boxes only by fields from Box model you can fill the content_objects dict after pagination. But you need to pass content_objects to __unicode__ somehow.

    How would you refactor this DB schema to make such queries easier?

    We have a similar structure. We store content_object in Box, but instead of object_id and content_object we use ForeignKey(Box) in Apple and Chocolate. In Box we have a get_object method to return the Apple or Chocolate model. In this case we can use select_related, but in most of our use-cases we filter Boxes by content_type. So we have the same problems like your 5th option. But we started our project on Django 1.2 when there was no prefetch_selected.

    If you rename farm/factory to some common name, like creator, will prefetch_related work?

    About your option 6

    I can’t say anything against filling _content_object_cache.
    If you don’t like to deal with internals you can fill a custom property and then use

    apple = getattr(self, 'my_custop_prop', None)
    if apple is None:
        apple = self.content_object
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've been wondering, suppose I have a model with an attribute that in every
Let's suppose I have a Discussion model, and that a discussion can be tagged.
Suppose I have an model object Event that contains a Venue . When I
Suppose you have to model several classes that should have composite properties like dimensions
Suppose I have an Comment model that belongs_to a Post model. I want to
Suppose that I have the model Foo in GAE and this query: query =
Suppose I have a model Stock that has several StockPartition (its a property called
suppose I have a model and a view ,ths view have two method:one is
Suppose I have a simple model, such as Record: @Model public class Record {
Suppose I have got a model ArticleVersion in my project which is defined as:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.