Skip to content
Advertisement

Alias one-to-many relationship

I have a User object and that user object can have various Answers objects tied to it.

I would like to be able to do the following:

u=User.objects.get(pk=...)
u.answers()

This is the current way I am doing it — via a @property, but I’m wondering if there is a cleaner or more ‘built-in’ way to do this:

class Answer(models.Model):
    user        = models.ForeignKey('User')
    tag         = models.CharField(max_length=140)
    upvotes     = models.IntegerField()

class User(models.Model):
    email       = models.CharField(max_length=80, unique=True)
    name        = models.CharField(max_length=140, blank=True, null=True)

    @property
    def answers(self):
        return self.answer_set.all()

Is there a better way to do this?

Advertisement

Answer

Use related_name on the FK definition. cf https://docs.djangoproject.com/en/3.1/topics/db/queries/#backwards-related-objects

you’ll do something like:

u.answers.all()
Advertisement