Home » Django » Django accessing ForeignKey model objects

Django accessing ForeignKey model objects

Posted by: admin December 31, 2017 Leave a comment

Questions:

Let’s say I have the following:

class Employee(models.Model):
    firstName = models.CharField(max_length = 30)
    lastName = models.CharField(max_length = 30)

class License(models.Model):
    employee = models.ForeignKey(Employee)
    type = models.CharField(max_length = 30)

and in a custom management command, I’m pulling in all the Employee objects with employees = Employee.objects.all()… how can I access associated License objects for each employee object? I have seen questions that talk about using ContentType for this purpose, but I’m confused on it’s practical use. Can anyone provide an example on how to use ContentType (or another solution) in this context?

Answers:
employee.license_set.all()

https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects