#On the admin page, how can I show the datetime of an fk-related table?

16 messages · Page 1 of 1 (latest)

timber gyro
#

`class Endpoint(models.Model):
server = models.ForeignKey(Server, on_delete=models.CASCADE)
endpoint = models.CharField(max_length=50)

def __str__(self):
    return self.endpoint

class JSON(models.Model):
server = models.ForeignKey(Server, on_delete=models.CASCADE)
check_datetime = models.DateTimeField()
endpoint = models.ForeignKey(Endpoint, on_delete=models.CASCADE)
json = models.JSONField()

def __str__(self):
    return "{}-{}-{}".format(self.server, self.check_datetime, self.endpoint)`
#

OK, so I have a fairly simple set of models here.

#

Basically I'm pulling data from someone else's API and saving it (and processing it and displaying it of course)

#

I would like the admin page to show the datetime on which the JSON was pulled last for each endpoint

#

It's no problem to do this in a view, but I'm not clear on how I could do this in the admin page itself.

#

My list_display for Endpoint would be ["server", "endpoint", "last_pulled"] , where last_pulled is the latest check_datetime for this endpoint.

#

hope that makes sense. A pointer in the right direction would be appreciated.

timber gyro
#

On the admin page, how can I show the datetime of an fk-related table?

vestal barn
#

You probably want to override model admin's queryset, adding annotation to it, and then method that reads it (since before you couldn't read it directly for some reason, iirc)

#

e.g. example:

@admin.register(models.Platform)
class PlatformAdmin(admin.ModelAdmin):

    ordering = ('priority', )
    list_display = ('name', 'icon', 'priority', 'build_count')

    def build_count(self, obj):
        return obj.build_count

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        qs = qs.annotate(build_count=Count('build'))
        return qs
timber gyro
#

Interesting, I wouldn't have thought of that. I'll give it a try, thank you friend.

vestal barn
#

You can as well just make only a admin or model method, but on list view it might inefficient.

timber gyro
#

I'm not planning on having any regular views for this, just the admin.

vestal barn
#

admin also can be made painfully slow without much effort

#

But generally both ways are your options

timber gyro
#

Annotate looks perfect.