I have a User
object and that user object can have various Answer
s 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?
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.