Django: How to order a set of queries in a field in multi-user ManyToManyField models (via)

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: Europe, South Asia and North Asia

Now I want to get all the β€œpublished” orders for the digital_release_date albums in the European region?

Can anyone tell me how to do this with an SQL query?

Thanks:)

+4
source share
3 answers

EDIT

Sorry, my mistake! Now that should work. I tried it at home ...

 Album.objects.filter( published=True, albumregionreleasedate__region__name='Europe' ).order_by( 'albumregionreleasedate__digital_release_date' ) 

Here is help for future doubts

Hope it works now!

+4
source

Well, since you are using Django ORM, you probably do not want to do this "by SQL query."

If you always want to order them (by default) this way, I would think that the best solution would be to put the ordering attribute in your pass-through Meta inner class model:

 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 need only one query that does this without using the default order ... I need to think about it more.

0
source

I think you could do something like:

 Region.objects.get(name='Europe').album_set.filter(published=True).order_by('digital_release_date') 
0
source

All Articles