Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get all related values of the model

These are my models

class Order(models.Model):
    name = ...

class OrderDetail(models.Model)
    order = models.OneToOneField(Order,null=False)
    comment = ...

class LastUpdate(models.Model)
    order = models.OneToOneField(Order,null=False)
    date = ...

When I write Order.objects.all().values() it gives me a list which only contains name But I need to get the name,orderdetail__comment,lastupdate__date values.

I can get them by writing

Order.objects.values('name','orderdetail__comment','lastupdate__date').all()

but there are a lot of related models to the order and I don't want to write all of them.

How can I get the all values of the related fields?

like image 572
brsbilgic Avatar asked Oct 20 '25 05:10

brsbilgic


1 Answers

First, you query by

orders = Order.objects.select_related('orderdetail__comment', 'lastupdate__date')

then, get values by

orders.values('name', 'orderdetail__comment', 'lastupdate__date')
like image 144
iMom0 Avatar answered Oct 21 '25 18:10

iMom0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!