我有以下型号:
class Merchant(BaseModel):
user = OneToOneField(settings.AUTH_USER_MODEL, related_name='merchant', primary_key=True)
class MerchantExtended(BaseModel):
merchant = OneToOneField(Merchant, related_name='extended', primary_key=True)
billing_address = TextField()
在保存包含Merchant和MerchantExtended数据的表单时,我希望能够这样做:
user = get_user_from_somewhere()
merchant = Merchant(user=user)
# Implicitly does get_or_create() and sets merchant.extended.merchant
merchant.extended.billing_address = '123 Main St'
# Implicitly does merchant.extended.save()
merchant.save()
以上内容是否已存在,或者是否需要覆盖某些模型属性/方法才能实现此目的?
答案 0 :(得分:2)
我认为Django的update_or_create
可以在这里使用:
merchant = Merchant.objects.get(user=request.user)
ext_merchant, created = MerchantExtended.objects.update_or_create(
merchant=merchant, defaults={'billing_address': '123 Main St'}
)