Django-Admin filter on 'backwards' foreign key

387 views
Skip to first unread message

Till Backhaus

unread,
Jan 5, 2010, 9:52:03 AM1/5/10
to django...@googlegroups.com
Hi Django Users,

how do I filter the 'backwards' part of a foreign key in the admin?

I have two Models: Media and MediaTranslation. MediaTranslation has a
ForeignKey
to Media (I included the Model definitions below).

I want to filter Media objects that have (or don't have) a title in a
certain
language. list_filter however doesn't support this.

#the following example doesn't work for various reasons
class MyModelAdmin(admin.ModelAdmin):
list_filter = ('myothermodel__sth')

The filters themselves are trivial however:
Media.objects.filter(mediatranslation__language='<lang>')
Media.objects.exclude(mediatranslation__language='<lang>')

Did someone solve this problem already? How can I implement it?
Someone on
#django told me I couldn't do it even if I wrote my own filterspecs?
I really need this feature and I don't care if I get my hands dirty in
the
process (like to bypass list_filter). Will I really need to abandon
the changelist_view?

Thank you guys in advance.

Till Backhaus


These are the relevant models:
#app/models.py
from django.db import models
from tagging.fields import TagField
import tagging

class Media(models.Model):
tags=tagging.fields.TagField()

provider=models.ForeignKey(Provider,null=True,blank=True)

publish_start=models.DateTimeField(blank=True,null=True)
publish_end=models.DateTimeField(blank=True,null=True)
published=models.BooleanField(default=False,db_index=True)

date_added=models.DateTimeField(auto_now_add=True)
owner_group=models.ForeignKey(Group)
owner=models.ForeignKey(User)
import_no=models.IntegerField(blank=True)
tagging.register(Media,tag_descriptor_attr='tag_list')

class MediaTranslation(models.Model):
media=models.ForeignKey(Media)
language=models.CharField(max_length=2,choices=settings.LANGUAGES)
title=models.CharField(max_length=255)

class Meta:
unique_together=('media','language')

def __unicode__(self):
return self.title

Shawn Milochik

unread,
Jan 5, 2010, 10:01:22 AM1/5/10
to django...@googlegroups.com
If you change this:

media=models.ForeignKey(Media)

to this:
media=models.ForeignKey(Media, related_name = 'media_translations')

in your MediaTranslations model, then you can filter your Media queryset by referring to its media_translations.

Example:

media.objects.filter(media_translations__language = 'English') #note the double underscore

Shawn

Shawn Milochik

unread,
Jan 5, 2010, 10:02:18 AM1/5/10
to django...@googlegroups.com
Sorry, I completely missed the part of the question where you said you wanted to do it in the Django Admin. That I don't know about.

Shawn

tback

unread,
Jan 6, 2010, 8:10:15 AM1/6/10
to Django users
Hi Shawn, thanks for your help anyway! Anyone else?

Till Backhaus

Reply all
Reply to author
Forward
0 new messages