2009-11-26 86 views
2

我的模式是:如何通過GenericForeignKey訂購?

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"] 

這種排序不能正常工作。基於GenericForeignKey設置默認排序的正確方法是什麼?

回答

1

不可能的,因爲沒有方法來檢索要加入什麼表(和連接表可能不包含created_at字段)

的溶液可非規範化:

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 (__)