Django Admin: How to display value of fields with list_display from two models which are in oneToOne relation?
Finally!!! I solved it. As I thought it was simple, but I had to do it other way around and with multi table inheritance:
models.pyclass Member(models.Model): ID = models.AutoField(primary_key=True) FIRST_NAME = models.CharField('First name', max_length=50) LAST_NAME = models.CharField('Last name', max_length=50)# Using multi table inheritance - automaticly creates one to one fieldclass MemberDetail(Member): DATE_OF_BIRTH = models.DateField('Date of birth') EMAIL = models.EmailField('E-mail') PHONE = models.CharField('Phone', max_length=15)
Now for admin.py
admin.pyclass MemberDetailAdmin(admin.ModelAdmin): list_display = ("FIRST_NAME", "LAST_NAME", "DATE_OF_BIRTH", "EMAIL", "PHONE")admin.site.register(MemberDetail, MemberDetailAdmin)
That's it. Maybe, there is other solutions, but this is good for me.
In case anyone stumbles into this question/problem, I don't know a direct way to access fields from a OneToOne relationship, however, I was able to fix the problem with the following snippet. Notice that I CAN access OneToOne fields in list_filter
by using two '_' to access fields of an OneToOne, for example: modelB_fieldOne
.
@admin.display(description='Date') def transaction_date(self, purchase): return purchase.transaction.datelist_display = ('product', 'transaction_date')list_filter = ('product', 'transaction__date')
You should just be able to do 'member_detail__email'
, etc. in list_display
Since it's a 1-1 you should have a backref, and associated fields are referenced using two underscores.