Reputation: 633
So, after adding or removing a GenericRelation to one of my model classes nothing happens.
I try to makemigrations and it tells me no changes were detected. So there must be something wrong, because it should be hitting the database and try to apply some changes.
I followed Django example and I can't make the relationship work.
class Person(models.Model):
identity = models.CharField(max_length=13, verbose_name="ID")
name = models.CharField(max_length=255, verbose_name="Name")
board = GenericRelation('second_app.BoardMember') #Second Try
def __unicode__(self):
return self.identity
class Meta:
verbose_name = "Person"
verbose_name_plural = "People"
class Student(Person):
class Meta:
proxy = True
class Parent(Person):
class Meta:
proxy = True
class Teacher(Person):
board = GenericRelation('second_app.BoardMember') # first try
class Meta:
proxy = True
On a different app I have the following model.
class BoardMember(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id', for_concrete_model=False)
responsabilities = models.CharField(max_length=255)
At first I tried setting the Generic Relation on a proxy model. Nothing happened, then I tried setting it on the main Person class. Nothing. This is what I did to test the relation on the shell.
>>>from first_app.models import Teacher
>>>from second_app.models import BoardMember
>>>teacher = Teacher(identity='123456', name='Fermin Arellano')
>>>teacher.save()
>>>bm = Boardmember(content_object=teacher,responsabilities='Check stuff')
>>>bm.save()
>>>teacher.board.all()
[]
Following this example: https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#reverse-generic-relations
The expected result should be: [<Teacher: 123456>]
Am I doing something wrong? There are no errors showing anywhere. Data is saved properly, both the Teacher and BoardMemer objects were created successfully in my database.
Upvotes: 2
Views: 980
Reputation: 633
I just removed for_concrete_model=False
from the GenericForeignKey declaration. Although on Django´s documentation it clearly states that it has to be setted to false in order to use ProxyModels.
Everythings is working fine now.
EDIT.
I just realized that the problem persists. After further investigation I noticed that in order to get the generic relation to work I need to save the content_type_id
of the Person model, and not the proxy one. That is why deleting the for_concrete_model parameter helped, because this way I told Django to use the parents content type, and there it worked fine. Funny thing is that if I do the following the relations still works eventhough I have the content_type_id
of Person.
Teacher.objects.filter(board__isnull=False)
This returns all the teachers who are in the board.
This is really confusing, if you can shed some light on this mess I'll be very thankful.
Upvotes: 1