Search code examples
pythondjangoobjectgeneric-relations

Python get GenericRelation objects


I have the following code:

data/telephone.py:

class TelephoneNumber(models.Model):

    MOBILE = 0
    HOME = 1
    TELEFON_CHOICES = (
        (MOBILE, _("Mobile")),
        (HOME, _("Landline")),
    )

    object_id    = models.PositiveIntegerField()
    content_type = models.ForeignKey(ContentType)
    of           = generic.GenericForeignKey('content_type', 'object_id' )

    label = models.SmallIntegerField(choices=TELEFON_CHOICES) 
    number = models.CharField(max_length=20, blank=True)

model.py:

class Staff(models.Model):

    user = models.OneToOneField(User)
    telephonenumbers = GenericRelation(TelephoneNumber, related_query_name='telnumber')

No I want to provide a function to retrieve every telephone number of a user like this:

def get_telnumbers(self):
    tellist = []
    #print(self.telephonenumbers.all())
    for tel in self.telephonenumbers.all():
        tellist.append(tel)
    return tellist

The problem is, that the line print(self.telephonenumbers.all()) does not print any telephonenumbers, even though a lot have been provided. The returned dict is empty as well.

How can I access the GenericRelation objects saved within the Staff context?

Edit:

The following code:

for tel in TelephoneNumber.objects.all():
        print(tel)
        print(tel.of)

gives me every telephone number saved, and through tel.of the right staff user which the telephone number belongs to.

So why isn't self.telephonenumbers.all() working (self.user also returns the right user for which the telephone number should have been saved)?


Solution

  • I am still not sure why self.telephonenumbers.all() is not working.

    But I am using this (kind of ugly) workaround now:

    def get_telnumbers(self):
        for tel in TelephoneNumber.objects.all():
            if tel.of.id == self.id:
                ...
    

    If someone still has a better idea, I am open to that!