I have a feeling this is a very beginner mistake that Im making but Ive spent a lot of time on it and Im hoping someone can help point me in the right direction.
Anyway, here goes…
I have several models created. One model has a One to Many with another model. I am doing the following things in this order.
- Creating and appending a list of the “Many” objects I am creating.
- When all of them are done I am running a “bulk_create” to create the model objects for the “Many” model.
- I next create an object of the “One” model which fails. It fails because when I supply it the structure for the newly created “Many” objects I get an error saying it’s expecting an instance of the “Many” model. Im assuming it’s expecting a singular instance of the “Many” model and I am feeding it a list of more than one “Many” objects.
So, is there no way to create an instance of the “One” model and supply it numerous “Many” objects?
Also, can someone clarify for me if when having a One to Many relationship modeled I should make each model point to the foreign key of the other? Or is it only needed on one side of the relationship? If someone could explain this to me I would appreciate it.
I hope this makes sense but any input would be welcome.
A One-To-Many is defined as having a Foreign Key on the many side relating to an individual in a related table (the one). So you don’t assign numerous instances of the “Many” to the “One”. For each instance of the “Many” you assign it the reference to the instance of the “One”. There is no defined relationship on the side of the One that refers to the Many. Django provides an automatically created manager to let you access each side from the other within the ORM, but there’s no physical link from the One to the Many.
I appreciate the response, do could you maybe tell me what you think Im doing wrong? I have two model classes. “Invoice” and “Item”. The Invoice has many items.
In my Invoice class I have the following line (along with other fields):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
I am reading in many Items from parsing a JSON file. I create several Item objects (and store them in an array) and then create an object for the Invoice. When I try and create the Invoice object and set the appropriate line “item=item_objs” it fails and gives me an error. Whats the proper way to create “many” Item objects and then save them to the created Invoice object?
You’ve got the relationship backwards.
The Item (the “Many”) needs to have the Foreign Key to the “One” (Invoice).
You would create the Invoice first, and then create each of the individual Item, assigning each one (at the time it is being created) the reference to the Invoice.
Thank you for the help. I made the change and followed what you said. Everything seems to be being created like it should in the DB.
Removed issue about ID field as I figured it out.