Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 427
Ahsan Avatar asked Sep 07 '11 07:09

Ahsan


1 Answers

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!

like image 106
marianobianchi Avatar answered Oct 14 '22 00:10

marianobianchi