Issue
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?
Solution
This is a classic many-to-many relationship: https://docs.djangoproject.com/en/dev/ref/models/fields/#manytomanyfield
An editor suggests this article for an alternate explanation of Django's ManyToManyField
: https://www.sankalpjonna.com/learn-django/the-right-way-to-use-a-manytomanyfield-in-django.
Answered By - Peter DeGlopper
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.