Reputation: 3695
I am using django1.7 and I have two models.
One of my models I would like to specify the ordering by a field on a foreign model. The two models are linked by a foreign key.
Here are my two example models:
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.
I am trying to order the ObjectiveDetails by the language_code on the LanguageVersion model.
I have tried several attempts, but I cannot get it right. I have read the docs and searched SO & Google, but could not find the correct answer,
Upvotes: 2
Views: 484
Reputation: 524
add ordering by language_code to LanguageVersion and remove .language_code from ObjectiveDetails
Each foreign key you add will implicitly include all of its default orderings as well.
https://docs.djangoproject.com/en/1.7/ref/models/options/#ordering
your models will be like this
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']
Upvotes: 3