[Answer]-A query with 3 tables in django

1đź‘Ť

âś…

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.

👤Raymond Tau

0đź‘Ť

This assumes that what you have written is the only thing in your classes, i.e. that is your entire models.py file.

So, now you wish to know how you can link these tables together. The answer is simple, all you have to do is use one of the many relationship files that django provides in order to create a relationship between tables.

Now the relationship can be different, heck how the relationship works between the two tables may also be of importance. Django makes all of this possible, and take a look at the the documentation here. First one needs to establish the kind of relationship, so say a Person can have many Devices. So, this is how your new Person class would look like:

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

And this is how your Device class would look like:

class Device (models.Model)
   mobile = models.CharField(max_length=200)
   user = model.ForeignKey(Person)

Note that you do not change the Person class, this is how a Many-To-One relationship works in django. You can have a look at how this all works in the documentation link I provided above.

Now as for querying, you can simply do this:

Device.objects.filter(user__name='<name_you_want>')

0đź‘Ť

How can I make a query to get the devices used by the person “name”?

devices = Uses.objects.filter(person_name__name='name').values_list('person_device')
👤Burhan Khalid

Leave a comment