My model is:
我的模型是:
class Subscription(models.Model):
user = models.ForeignKey(User, related_name='subscription', editable=False)
following_content_type = models.ForeignKey(ContentType, editable=False)
following_id = models.PositiveIntegerField(editable=False)
following = generic.GenericForeignKey('following_content_type', 'following_id')
created_at = models.DateTimeField(auto_now_add=True, editable=False)
email_notification = models.BooleanField(default=False)
class Meta:
ordering = ["-following__created_at"]
This ordering isn't working. What's the proper way to setup default ordering based on a GenericForeignKey?
这种排序不起作用。基于GenericForeignKey设置默认排序的正确方法是什么?
1 个解决方案
#1
1
Not possible because no way to retrieve what table should be joined (and joined tables may not contain created_at field)
不可能,因为无法检索应该连接的表(并且连接的表可能不包含created_at字段)
The solution can be denormalization:
解决方案可以是非规范化:
class Subscription(models.Model):
[...]
following_created_at = models.DateTimeField(editable=False)
def save(self, *args, **kwargs):
following_created_at = following.created_at #that's the trick
super(Subscription, self).save(*args, **kwargs)
class Meta:
ordering = ["-following_created_at"] # Note that there is not dobuble underline (__)
#1
1
Not possible because no way to retrieve what table should be joined (and joined tables may not contain created_at field)
不可能,因为无法检索应该连接的表(并且连接的表可能不包含created_at字段)
The solution can be denormalization:
解决方案可以是非规范化:
class Subscription(models.Model):
[...]
following_created_at = models.DateTimeField(editable=False)
def save(self, *args, **kwargs):
following_created_at = following.created_at #that's the trick
super(Subscription, self).save(*args, **kwargs)
class Meta:
ordering = ["-following_created_at"] # Note that there is not dobuble underline (__)