django select_related().values() not returning all fields from 2 tables

Viewed 756

I have 2 tables, one child (Car) and the other parent (Dealership). I'm using the orm query Car.objects.all().select_related('dealership').values() to perform a left join which would give me all the fields from both cars and their related dealerships but that's not happening as I'm only able to get all the fields from the Car model.

class Dealership(models.Model):
    ...

class Car(models.Model):
    dealership = models.ForeignKey(Dealership, on_delete=models.CASCADE, null=True, default=None)
    ...

I read it in a different question that with .values() I'll have to explicitly mention all the required fields but there are just too many fields to enter manually. Is there a cleaner solution to this?

1 Answers

select_related is a performance booster and doesn't return you anything more than Car.objects.all() . read about it in https://docs.djangoproject.com/en/3.2/ref/models/querysets/#select-related

You should get dealerships from selected record. for example:

car = Car.objects.select_related('dealership').get(id=1)
dealers = car.dealership

If you are going to return a json from these info, i recommend you to user drf and serializer to handle this

Related