0

I have two following models (with OneToOne relation):

class Company(BaseModel):
    name = models.CharField(max_length=64)
    address_street = models.CharField(max_length=64)
    address_city = models.CharField(max_length=64)
    address_zipcode = models.CharField(max_length=6)
    # ...many other fields here...

class InvoicingData(BaseModel):
    company = models.OneToOneField(Company, null=True, blank=True)
    company_name = models.CharField(max_length=64)
    address_street = models.CharField(max_length=64)
    address_city = models.CharField(max_length=64)
    address_zipcode = models.CharField(max_length=6)

I want to auto-create InvoicingData model instance, when new Company is being added. I wanted to use signal to do so:

@receiver(post_save, sender=Company)
def create_invoicing_data(sender, instance, created, **kwargs):
    if created:
        # WHAT HERE?

Is there any simple, automated way to copy shared fields values from one model to another?

0

2 Answers 2

2

You can use Model._meta to get the list of the field names:

@receiver(post_save, sender=Company)
def create_invoicing_data(sender, instance, created, **kwargs):
    if created:

        invoice_fields = InvoicingData._meta.get_all_field_names()

        data = dict((field_name, getattr(instance, field_name))
                       for field_name in Company._meta.get_all_field_names()
                       if field_name != 'id' and field_name in invoice_fields)

        InvoicingData.objects.create(company=instance,
                                     company_name=instance.name,
                                     **data)
Sign up to request clarification or add additional context in comments.

Comments

1
@receiver(post_save, sender=Company)
def create_invoicing_data(sender, instance, created, **kwargs):
    if created:
        invdata = InvoicingData(company=instance)
        # set any other fields on invdata if desired
        invdata.save()

3 Comments

I also need to copy all other fields (address, etc)
You could use @catavaran's answer below, or simply set the fields manually, E.G., invdata.address_city = instance.address_city, etc.
In my case that seems to be a simpler solution. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.