django: How to order the queryset on a field in ManyToManyField (through) related models
I have these models
class Region (models.Model):
name = models.CharField (max_length = 255, blank = False)
class Album(TimeStampAwareModel):
title = models.CharField (max_length = 255, blank = False)
digital_release_date = models.ManyToManyField( Region, through="AlbumRegionReleaseDate", related_name="release_date_albums")
published = models.BooleanField (default = False)
.
.
class AlbumRegionReleaseDate(models.Model):
album = models.ForeignKey (Album)
region = models.ForeignKey (Region)
digital_release_date = models.DateField ()
开发者_如何转开发 class Meta:
ordering = ('-digital_release_date')
Suppose i have three regions i:e Europe, South Asia and North Asia
Now i want to get all "published" albums order by "digital_release_date" in Europe region?
Can anyone please tell me how to do this by SQL query?
Thanks :)
EDIT:
Sorry, my mistake! Now this should work. I tried it at home...
Album.objects.filter(
published=True,
albumregionreleasedate__region__name='Europe'
).order_by(
'albumregionreleasedate__digital_release_date'
)
Here is some help to future doubts
Hope it works now!
Well, since you are using Django's ORM, you probably don't want to do it 'by SQL query'.
If you always want to order them (by default) that way, I would think the best solution would be to put an ordering attribute on your through model's Meta inner class:
class AlbumRegionReleaseDate(models.Model):
album = models.ForeignKey(Album)
region = models.ForeignKey(Region)
digital_release_date = models.DateField()
class Meta:
ordering = ('region', 'digital_release_date')
If you want just one query that does that, without using the default ordering, ... I'll have to think some more.
I think you could do something like:
Region.objects.get(name='Europe').album_set.filter(published=True).order_by('digital_release_date')
精彩评论