Showing Customer Information With Order
Introduction
In order that admin users can effectively control customers' orders, I decided to show some customers' information attached to the order that they created.
Analysis
In Django, we can show model fields with list_display
(opens in a new tab).
For relationship fields such as ForeignKey
(opens in a new tab) or ManyToManyField
(opens in a new tab), however, are different story.
ForeignKey
will explicitly show the value that__str__()
method returns.ManyToManyField
is not supported since it makes Django to carry out different SQL commands on each rows of table which is quite costly.
As of Feburary 6th, 2024, we can use
__
lookups in dev version, but still not in 5.0 version.
I implemented this feature by creating extra methods with display
decorator (opens in a new tab).
Solution
Creating OrderAdmin
class
Connecting Order
model with OrderAdmin
class with register
decorator (opens in a new tab).
Creating method for customer name
I created get_customer_full_name()
method with using display
decorator that returns the full name of customers.
The second parameter obj
indicates the queryset of Order
connected to OrderAdmin
, and I return
ed first_name
and last_name
of user
that is connected with ForeignKey
.
Then, I put it into list_display
array.
Creating customer contact info
I did same thing over again for customers' contact info and put it in list_display
.
Creating OrderAdmin
class
Connecting Order
model with OrderAdmin
class with register
decorator (opens in a new tab).
Creating method for customer name
I created get_customer_full_name()
method with using display
decorator that returns the full name of customers.
The second parameter obj
indicates the queryset of Order
connected to OrderAdmin
, and I return
ed first_name
and last_name
of user
that is connected with ForeignKey
.
Then, I put it into list_display
array.
Result
Works like a charm as shown image below.