2015-09-22 65 views
1

我使用的是django1.7,我有兩個模型。django models.py使用外國字段排序

我的模型之一,我想指定ordering在外國模型的字段。這兩個模型通過外鍵鏈接。

這裏是我的兩個例子型號:

class ObjectiveDetails(models.Model, FillableModelWithLanguageVersion): 
    user = models.ForeignKey(User) 
    language_version = models.ForeignKey('LanguageVersion') 
    field = models.TextField(null=False, blank=False, max_length=5000) 
    objective_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False) 
    objective_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False) 

    class Meta: 
     ordering = ['language_version.language_code', 'id'] 

class LanguageVersion(models.Model): 
    """Language version selection for a user""" 
    user = models.ForeignKey(User) 
    language_code = models.CharField(max_length=32) 
    language_code_disabled = models.BooleanField(default=False) 
    language_version_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False) 
    language_version_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False) # the date the language version is updated when the user changes their subscription type. 

我想通過在LanguageVersion模型作爲language_code訂購ObjectiveDetails。

我已經嘗試了幾次嘗試,但我無法弄清楚。我已閱讀文檔和搜索SO &谷歌,但找不到正確的答案,由LANGUAGE_CODE

+1

你嘗試'ORDER_BY( 'LANGUAGE_VERSION')'? –

回答

1

添加順序來LanguageVersionObjectiveDetails

您添加的每個外鍵刪除.language_code 也隱含地包含了它的所有默認排序。

https://docs.djangoproject.com/en/1.7/ref/models/options/#ordering

您的模型會是這樣

class ObjectiveDetails(models.Model, FillableModelWithLanguageVersion): 
    user = models.ForeignKey(User) 
    language_version = models.ForeignKey('LanguageVersion') 
    field = models.TextField(null=False, blank=False, max_length=5000) 
    objective_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False) 
    objective_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False) 

    class Meta: 
     ordering = ['language_version', 'id'] 

class LanguageVersion(models.Model): 
    """Language version selection for a user""" 
    user = models.ForeignKey(User) 
    language_code = models.CharField(max_length=32) 
    language_code_disabled = models.BooleanField(default=False) 
    language_version_timestamp_added = models.DateTimeField(auto_now_add=True, auto_now=False) 
    language_version_timestamp_updated = models.DateTimeField(auto_now=True, auto_now_add=False) # the date the language version is updated when the user changes their subscription type. 

    class Meta: 
     ordering = ['language_code'] 
+0

demonno,謝謝,這很好 - 我有點尷尬,我錯過了。 – user1261774