I have two models in different apps: ModelA
and ModelB
. They have a one-to-one relationship. Is there a way django can automatically create and save ModelB
when ModelA
is saved?
class ModelA(models.Model): name = models.CharField(max_length=30) class ModelB(models.Model): thing = models.OneToOneField(ModelA, primary_key=True) num_widgets = IntegerField(default=0)
When I save a new ModelA
I want a entry for it to be saved automatically in ModelB
. How can I do this? Is there a way to specify that in ModelA
? Or is this not possible, and I would just need to create and save ModelB
in the view?
Edited to say the models are in different apps.
To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).
One-to-one fields:This is used when one record of a model A is related to exactly one record of another model B. This field can be useful as a primary key of an object if that object extends another object in some way. For example – a model Car has one-to-one relationship with a model Vehicle, i.e. a car is a vehicle.
ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.
Take a look at the AutoOneToOneField
in django-annoying. From the docs:
from annoying.fields import AutoOneToOneField class MyProfile(models.Model): user = AutoOneToOneField(User, primary_key=True) home_page = models.URLField(max_length=255) icq = models.CharField(max_length=255)
(django-annoying is a great little library that includes gems like the render_to decorator
and the get_object_or_None
and get_config
functions)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With