Eli Per
Eli Per

Reputation: 97

Is there any way to retrieve Objects from ManyToManyFields in the order they were added?

I have a bunch of Recipes and would like the User to have the option to save the ones he likes. I originally made it with a ManyToManyField on the Recipe model to to the User model but the problem was i wasn't getting them back in order that they were saved. Is there any way to do this?

If not, what should i do instead to be able to keep the order? Make a third model with a date field and link the two? Seems like a bit of a waste.

Any help would be nice. Thank you

Upvotes: 1

Views: 27

Answers (1)

ruddra
ruddra

Reputation: 51988

If not, what should I do instead to be able to keep the order? Make a third model with a date field and link the two?

You are right. But for this, you can use through in your M2M relation. For example:

class User(models.Model):
    recipes = models.ManyToManyField(Recipe, through='UserRecipes')



class UserRecipies(models.Model):
     recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='user_recipes')
     user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recipes_per_user')
     created_at = models.DateTimeField(auto_now_add=True)

     class Meta:
        ordering = ['created_at',]

Upvotes: 3

Related Questions