How to sort related objects based on the timestamp of when we are associating the two objects?

23 Views Asked by At

i'm trying to sort objects based on the time when i associate the two objects.

For example, i have these two models:

class Album(models.Model):
    title = models.CharField(max_length=255)
    release_date = models.DateField()
    order = models.IntegerField(blank=True, null=True, help_text="The order of albums to be displayed.")


class Artist(models.Model):
    name = models.CharField(max_length=255)
    stage_name = models.CharField(max_length=125)
    is_active = models.BooleanField(default=True)
    albums = models.ManyToManyField(Album, blank=True)

I have an Album model, that have an order field to sort the priority of the album when we display it on the API. Now, of course it is working when i sort the albums based on the order field:

artist = Artist.objects.get(id=76)
album1 = Album.objects.create(title="Untitled Album", order=2)
album2 = Album.objects.create(title="Magical Nights", order=1)
artist.albums.add(album1, album2)
albums = Album.objects.filter(artist=artist).order_by('order')
print(albums)

>> <QuerySet [<Album: Magical Nights>, <Album: Untitled Album>]>

But when i have some albums with the same priority, i want to also sort the objects based on the timestamp of when i associate the item. Something like this:

artist2 = Artist.objects.get(id=77)
new_album1 = Album.objects.create(title="Sapphire Blue", order=1)
new_album2 = Album.objects.create(title="Now We're Strangers", order=2)
new_album3 = Album.objects.create(title="Fight For You", order=1)
artist2.albums.add(new_album3)
artist2.albums.add(new_album2)
artist2.albums.add(new_album1)

albums = Album.objects.filter(artist=artist2).order_by('order')
print(albums)

>> <QuerySet [<Album: Sapphire Blue>, <Album: Fight For You>, <Album: Now We're Strangers>]>

My expected result is that when we filter based on order and the timestamp, it will be something like this:

>> <QuerySet <Album: Fight For You>, [<Album: Sapphire Blue>, <Album: Now We're Strangers>]>

If i only sort based on order, it might not always sort based on the time when i add the album to the artist. Is there a way to do this? I can't seem to find the right keyword to search or method to do this. Thank you so much.

0

There are 0 best solutions below