22

For an example, let's say I'm running an online meat shop. Orders come in "parcels", which contain various types of meat.
My models could look something like this:

class Parcel(models.Model):
    customer_address = models.CharField()
    date_wanted = models.DateField()
    meats = ?
class Meat:
    name = models.CharField()
    cost = models.DecimalField(4, 2)

So, I would have set of Meat objects that represent all the different meats I can put in a parcel. Then, the parcel contains a large amount of meat objects, as well as the address it needs to be shipped to, etc.
How do I store an unknown amount of foreign keys in a Django model?

2 Answers 2

24

This is a classic many-to-many relationship.

https://docs.djangoproject.com/en/dev/ref/models/fields/#manytomanyfield

1
  • Doh! This is originally what I thought it was for, but then I misread some things. Thank you very very much!
    – Jaxkr
    May 14, 2013 at 23:26
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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.