Login

SelectRelatedManager

Author:
realmac
Posted:
September 15, 2011
Language:
Python
Version:
1.2
Tags:
admin manager select queryset
Score:
0 (after 0 ratings)

Because select_related() only works on ForeignKeys that are not null or blank, when you are customizing the admin, even if you set "list_select_related=True" you can still end up with way too many querys in the Admin changelist. By adding this code to your model you can decrease the queries dramatically.

I found I needed this when I was working with Django apps with a lot of legacy data and I couldn't set the ForeignKey null=False.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class SelectRelatedManager(models.Manager):
    def get_query_set(self):
        return super(SelectRelatedManager, self)\
            .get_query_set()\
            .select_related('organization')

class SomeModel(models.Model):
    ...
    organization = models.ForeignKey(Organization, blank=True, null=True)
    ....

    objects = SelectRelatedManager()

More like this

  1. RelatedNullFilterSpec: django-admin custom filter all/null/not null/choices by Codeko 4 years, 7 months ago
  2. Hyperlink read-only ForeignKey objects in admin to their change pages by strangefeatures 3 years, 4 months ago
  3. django-admin custom filter: IS NULL/IS NOT NULL by Eloff 5 years, 2 months ago
  4. Making prepopulate_from work with ForeignKeys and other sorts of choice fields by josho 6 years, 8 months ago
  5. Left Outer join Q object by karsu 7 years, 11 months ago

Comments

Please login first before commenting.