使用来自相关对象的数据创建模型实例

Create model instance using data from related object

我有以下两个模型(具有 OneToOne 关系):

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)

我想在添加新公司时自动创建 InvoicingData 模型实例。我想使用信号来这样做:

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

是否有任何简单、自动化的方法可以将共享字段值从一个模型复制到另一个模型?

@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()

您可以使用 Model._meta 获取字段名称列表:

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