I have to use .get()
because there’s a lot of code that follows using dot notation.
sof = ServiceOrder.objects.get(id=sof_id)
if sof is None:
return ['Service Order ID does not exist']
but it seems that I can get FK fields from .filter()
only ? ('acc_manager__emp_name'
)
sof = ServiceOrder.objects.get(id=sof_id).values(
'so_number', 'status',
'acc_manager__emp_name'
).first()
if not sof:
return ['Service Order ID does not exist']
How do I extract acc_manager__emp_name
from get()
so that I can reference sof.acc_manager__emp_name
?
The filter
and values
functions return querysets, get
returns an instance of the model.
If you’re chaining query api functions, the function not returning a queryset must be the last function call in the list.
In other words, it’s valid to do something like:
SomeModel.objects.values(...).get(...)
It’s also redundant to use both first
and get
in a query. The first
function also returns an instance.
For what you have, simply replacing get
with filter
should do what you need it to do.
In Django ORM, backward and forward relations are available on all objects.
sof = ServiceOrder.objects.get(id=sof_id)
after you get the sof object, just follow the relation
emp_name = sof.acc_manager.emp_name
1 Like