问题
I have three models : Domain
Topic
Post
Topic
has a foreign key
to Domain
and Post
has a foreign key
to Topic
.
Post
has a field updated_on
.
I want to annotate last_updated
field in Domain
queryset which would contain the latest post object from Post
.
Edit 1: Added models definition:
class Board(models.Model):
name = models.CharField(max_length=30, unique=True)
description = models.CharField(max_length=50)
creation_time = models.DateTimeField(auto_now_add=True)
class Topic(models.Model):
subject = models.CharField(max_length=300, unique=True)
board = models.ForeignKey(Board, on_delete=models.SET_NULL, related_name='topics', null=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='topics', null=True)
created_on = models.DateTimeField(auto_now_add=True)
views = models.PositiveIntegerField(default=0)
class Post(models.Model):
message = models.CharField(max_length=5000)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='posts', null=True)
created_on = models.DateTimeField(auto_now_add=True)
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, related_name='posts', null=True)
updated_on = models.DateTimeField(default=timezone.now)
来源:https://stackoverflow.com/questions/61291587/django-annotate-with-field-of-related-name-of-related-name