Python 这是拯救儿童的好做法吗;“保存”;父对象的方法?
如果有两种模式称为公司和植入。显然,一家公司可以进行多次植入,因此植入类中有一个外键领域 有一个法国API,它将帮助公司收集数据。 所以我为查询API的公司定义了一个干净的方法。 同样的电话也将返回有关公司植入的信息 我在想:“为什么不在拯救公司的同时创建(并保存)植入?” 我可能能够在公司的save方法中使用原子事务来实现这一点 到目前为止,我已经做到了这样的事情(虽然没有完全测试过…): 我的问题(最后…)是: 这是否被视为重写save方法的良好实践?(我有我的怀疑…) 如果没有,我最好的做法是什么?将所有这些“API调用”转换为任何表单验证Python 这是拯救儿童的好做法吗;“保存”;父对象的方法?,python,django,django-models,Python,Django,Django Models,如果有两种模式称为公司和植入。显然,一家公司可以进行多次植入,因此植入类中有一个外键领域 有一个法国API,它将帮助公司收集数据。 所以我为查询API的公司定义了一个干净的方法。 同样的电话也将返回有关公司植入的信息 我在想:“为什么不在拯救公司的同时创建(并保存)植入?” 我可能能够在公司的save方法中使用原子事务来实现这一点 到目前为止,我已经做到了这样的事情(虽然没有完全测试过…): 我的问题(最后…)是: 这是否被视为重写save方法的良好实践?(我有我的怀疑…) 如果没有,我最好的做
from django.db import models, transaction
import requests
class Company(models.Model):
#this is the french "official" key of any company :
siren = models.CharField("Numéro SIREN", max_length=9, blank=True, unique=True)
#this is a field which can be found on the french API
denomination = models.CharField("Dénomination", max_length=150, blank=True)
def clean(self):
if self.siren:
#call to the french API
s = requests.Session()
r = s.get("https://entreprise.data.gouv.fr/api/sirene/v3/unites_legales/"+self.siren)
if r.status_code:
#'unite_legale' translates (here) to 'company'
self.denomination = r.json()['unite_legale']['denomination']
#'unite_legale' translates (here) to 'implantation'
self.implantations = r.json()['unite_legale']['etablissements']
def save(self, *args, **kwargs):
self.clean()
with transaction.atomic():
super().save(*args, **kwargs)
for implantation in self.implantations:
implantation = Implantation(siret=etab['siret'])
implantation.save()
class Implantation(models.Model):
#this is the french "official" key of any implantation of a company :
siret = models.CharField("Numéro SIRET", max_length=14, blank=False, unique=True)