Is it possible to apply list_filters for parent's object's fields in django?
I want to display the timestamp stored in my parents model to be shown in my model. Also, I want to display it in german format. This is not the problem, but of course I want to be able to sort by this timestamp.
One solution would be to create a new DateTimeField in model B, but then I would store redundant information. How can I do that with Django?
For example:
#models.py
class A(models.Model):
timestamp = models.DateTimeField(null=True)
class B(models.Model):
key_to_a = models.ForeignKey(A, on_delete=models.CASCADE, null=True)
##########
#admin.py
class BAdmin(admin.ModelAdmin):
def german_timestamp(self, B):
return B.key_to_a.timestamp.strftime('%d-%m-%Y %H:%M:%S')
german_timestamp.short_description = "timestamp"
list_display = ("german_timestamp")
list_filter = ("german_timestamp") #This breaks my code as there is no field called "german_timestamp"
I cannot post a comment, which is maybe is the case, but:
Have you tried to set a __str__ method in your A model? Or a german_timestamp method in the A model (if you plan to use other formats for your date) that returns A.timestamp in the format you want.
This way you could just set key_to_a in your list_filter and it will use the method of the A model.