todel23
todel23

Reputation: 108

How to create one to one field with Django for existing table?

We already have a model, let's say, Product. And we want to extend it into 'one to one relationship', let's say, ProductDetails. How do it in such way, that for each existing row of Product model row ProductDetails is created automatically? with some default vaules.

Does Django provide such tool? The task seems pretty regular for me, but I can't find any native solution.

Upvotes: 1

Views: 832

Answers (1)

Yeamin Mahmud
Yeamin Mahmud

Reputation: 67

here is an answer to your question: https://stackoverflow.com/a/63323183/10602634

django signals can be used to create, update or delete on change of an object.

in your case:

from django.dispatch.dispatcher import receiver

class ProductDetails(models.Model):
    product =  models.OneToOneField(Product, on_delete= models.CASCADE)
    '''rest'''

wrap a function using receiver

@receiver(post_save, sender=Product)
def add_details(sender, instance, created, **kwargs):
    if created:
        ProductDetails.objects.create(product=instance)
        return ProductDetails

django documnetation on receiver covers the topic https://docs.djangoproject.com/en/3.2/topics/signals/#receiver-functions

Upvotes: 1

Related Questions