Reputation: 97
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
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