24👍
This is a classic many-to-many relationship.
https://docs.djangoproject.com/en/dev/ref/models/fields/#manytomanyfield
0👍
A classic many-to-many relationship would work until you have a quantity of a certain meat in a parcel and you want to calculate the total price.
The many-to-many relationship can only give you the set of the types of meats in a parcel.
You would need another model to store the quantity information. In Django, this is done with the "through" model in the many-to-many relationship https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.through
class Parcel(models.Model):
customer_address = models.CharField()
date_wanted = models.DateField()
meats = models.ManyToManyField(Meat, through=MeatInParcel)
class Meat(models.Model):
name = models.CharField()
cost = models.DecimalField(4, 2)
class MeatInParcel(models.Model):
parcel = models.ForeignKey(Parcel, on_delete=models.CASCADE)
meat = models.ForeignKey(Meat, on_delete=models.CASCADE)
quantity = models.IntegerField()
see https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany for more details on how to use add(), create(), or set() to create relationships
- [Django]-Django OneToOneField – in which model should I put it?
- [Django]-Django test client gets 301 redirection when accessing url
- [Django]-Iterate over model instance field names and values in template