Django models ManyToManyField always adding item to list

Viewed 10

I'implemented two models, Card and Dish. I used many-to-many relationship because Dish can be in many cards. Not sure if I did that right because any Dish that I add is automatically added to every Card. Here is the code:


class Dish(models.Model):
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(max_length=1000)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    preparation_time = models.IntegerField()
    date_added = models.DateField(auto_now_add=True)
    update_date = models.DateField(auto_now=True)
    vegan = models.BooleanField(default=False)

    def __str__(self):
        return self.name


class Card(models.Model):
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(max_length=1000)
    date_added = models.DateField(auto_now_add=True)
    update_date = models.DateField(auto_now=True)
    dishes = models.ManyToManyField(Dish, blank=True)

    def __str__(self):
        return self.name

An the problem in admin panel looks like this: enter image description here

When I create a dish it is alway added to every card.
Any help please I'm just begining to learn sql and django ORM

1 Answers

Dishes being in that admin field doesn't mean they're actually selected, that's just the Multi-Select field. Only the ones that are highlighted are actually in the field. and you do +Click to toggle if they're selected or not

I guess that was the best way to show a Many-to-Many field, tho it might be confusing to use imo.. That's why I always just edit them in the shell, especially when there gets 100+, 200+ items.

Related