Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Django automatically create a related one-to-one model?

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.

like image 315
vagabond Avatar asked Oct 30 '09 21:10

vagabond


People also ask

How do I create a one to many relationship in Django?

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).

What is Django one to one field?

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.

What is ForeignKey in Django?

ForeignKey is a Django ORM field-to-column mapping for creating and working with relationships between tables in relational databases.


1 Answers

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)

like image 176
John Paulett Avatar answered Sep 21 '22 06:09

John Paulett