GenericForeignKey and Proxy Models

46 views
Skip to first unread message

Fermin Arellano

unread,
Oct 13, 2015, 12:05:56 PM10/13/15
to Django users
I am using proxy models (Student, Teacher, Parent) from a base class Person. 

I also have a class called BoardMember which uses the content type framework. In Boardmember I declared a GenericForeignKey(content_type, object_id, for_concrete_model=False).

In my proxy model (Teacher) I declared a generic relation   board = GenericRelation(Boardmember)  .

In my admin I have a model called Board and BoardMember is a TabularInline of Board. 

So, whenever I add a new Teacher as a Boardmember, the content_type_id being saved is the one of Teacher. This is the normal behavior, since I set for_concrete_model to False so it can reference Proxy models. So everything great. The problem is when I am trying to make a reverse relationship. When I do the following the relationship doesnt work. 

>>>Teacher.objects.filter(board__isnull=True)
[]

This instruction should return all the Teacher objects who are related as a BoardMember. 

Now if I do the following changes I can get it to work.

- First I remove for_concrete_model = False from my GenericForeignKey. This will default it to true. 
- Now whenever I associate a Teacher as a BoardMember in my admin, the content_type_id being saved is the one of Person, the base class. 

Now I can do the following:

>>>Teacher.objects.filter(board__isnull=True)
[<Teacher: Fermin> <Teacher:Mr. John>]

So now it does work, funny things is that the GenericRelation is set on Teacher and not Person. The content type saved was the one of Person and yet I can use the GenericRelation from Teacher object. This is really weird behavior. Can someone explain. I get the feeling very often that I have to be hacking solutions in Django Framework when things should be straight forward solutions. 

Thanks a lot!
Reply all
Reply to author
Forward
0 new messages