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

时间:2015-02-16 09:26:30

标签: python django django-models

我有两个以下模型(使用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?

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

2 个答案:

答案 0 :(得分:2)

您可以使用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)

答案 1 :(得分: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()