Skip to content
Advertisement

A query with 3 tables in django

I have 3 classes like this:

class Person (models.Model)
   name = models.CharField(max_length=200)

class Device (models.Model)
   mobile = models.CharField(max_length=200)

class Uses (models.Model)
   ....
 person_name =  models.ForeignKey(Person)
 person_device = models.ForeignKey(Device)

My question is: How can I make a query to get the devices used by the person “name”? Which needs to pass through the uses class.

Advertisement

Answer

Life will be easier if you use ManyToManyField, i.e. add this field to the Person model:

devices = models.ManyToManyField('Device', through='Uses')

Then, to get the list, you just need to get the devices attribute of the model object:

Person.objects.get(name="TheNameYouWant").devices

If you do not want to modify the model, the list of devices used by a person could be retrieved as below:

Device.objects.filter(uses__person_name__name="TheNameYouWant")

If Django say cannot resolve keyword “uses” into filed, please change to “uses_set”. I can’t remember which one is which.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement