Django annotate with 'field' of 'related_name' of 'related_name'

℡╲_俬逩灬. 提交于 2020-04-30 06:33:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!