Dino
Dino

Reputation: 1347

DJANGO ORM join on multiple tables

I have the following models:

class Timesheet(models.Model):
    work_packet
    logged_billable_hours

class WorkPacket(models.Model):
    type
    name
    purchase_order
    description

class PurchaseOrder(models.Model):
    customer

class Customer(Programme):
    name

the following queries:

my_timesheet_Q3 = me.timesheets.filter(date__gte=datetime.date(2019, 9, 1), date__lte=datetime.date(2019, 11, 30)).values('work_packet', 'logged_billable_hours')

my_timesheet_Q3_by_wp = my_timesheet_Q3.values('work_packet').annotate(wp_hours=Sum('logged_billable_hours')).order_by()

produces:

[{'work_packet': 1152, 'wp_hours': Decimal('384.00')}]

to the result I would like to add:

WorkPacket.type, WorkPacket.name, WorkPacket.purchase_order, WorkPacket.description, Customer.name

I know how to achieve it in plain SQL but I don't using DJANGO ORM. Can you help?

Upvotes: 0

Views: 42

Answers (1)

Daniel Holmes
Daniel Holmes

Reputation: 2002

You can add them to your .values like this using field lookups:

my_timesheet_Q3 = me.timesheets.filter(
    date__gte=datetime.date(2019, 9, 1),
    date__lte=datetime.date(2019, 11, 30)).values(
'work_packet', 'logged_billable_hours', 'work_packet__type', 'work_packet__name', 
'work_packet__purchase_order', 'work_packet__description',
'work_packet__purchase_order__customer__name')

Upvotes: 1

Related Questions