我需要使用shell将发票明细的元素添加到inlineformset_factory,我的模型是:
class InvoiceDetail(CreateUpdateMixin):
client = models.ForeignKey('client.Client', verbose_name=_('Factura A'), blank=True, null=True, default=None)
date = models.DateField()
tax = models.FloatField()
concept = models.ForeignKey(ConceptDetail, null=True, blank=True, verbose_name=_('Clave Concepto'))
custom_concept = models.CharField(max_length=150, null=True, blank=True, verbose_name=_('Concepto'))
amount = models.IntegerField(verbose_name=_('Cantidad'))
fee = models.FloatField(verbose_name=_('Honorarios'))
duty = models.FloatField(verbose_name=_('Gastos'))
invoice = models.ForeignKey(Invoice, null=True, blank=True, related_name='detail_concepts')
class Invoice(CreateUpdateMixin):
invoice = models.CharField(max_length=15, verbose_name=_('Número de Factura'))
# Details to show when calls the invoice choice from menu in procedure
# for mabe is an addenda
title_addenda = models.CharField(max_length=80, verbose_name=_('Titulo Detalle Factura'))
detail_addenda = models.CharField(max_length=350, verbose_name=_('Detalle Factura'))
status = models.ForeignKey(StatusInvoice, null=True, blank=True)
我试过了,但没有用
In [54]: invoice_obj = Invoice.objects.get(invoice=100067)
Out[55]: <Invoice: 100067>
In [56]: inv_det = InvoiceDetail.objects.get(custom_concept='PROFESSIONAL FEES FOR THE PAYMENT OFEACH ANNUAL TAX ON PATENTS')
Out[57]: <InvoiceDetail: b'PROFESSIONAL FEES FOR THE PAYMENT OFEACH ANNUAL TAX ON PATENTS'>
In [58]: # create inlineformset_factory
In [59]: TestFormSet = inlineformset_factory(Invoice, InvoiceDetail, fields='__all__')
In [61]: test = TestFormSet(instance=invoice_obj)
In [62]: test.data
Out[62]: {}
In [63]: test.save()
Out[63]: []
我尝试按照django docs inline-formsets按照我的步骤正确的文档进行操作,我做错了吗?
已修改以添加更多详细信息
我有一个迁移脚本,我需要在Invoice中添加多个InvoiceDetail对象,因此我尝试转换为inlineformset_factory,认为这是正确的方法,但我不知道,如果直接添加InvoiceDetail到发票它没有维护所有InvoiceDetail它只保留最新,如果我修改我的模型发票到m2m InvoiceDetails我可以保留所有元素但我不能使用formset.all InvoiceDetail它只保留最新的。< / p>
这是我的脚本代码:
def _get_invoice_detail(self, key, complex_dictionary):
"""
For add correct data we need to create a formset so.
:param complex_dictionary:
:return:
"""
# from django.forms.models import inlineformset_factory
# InvoiceDetailFormSet = inlineformset_factory(Invoice, InvoiceDetail, fields='__all__')
# load all invoices from db
_db = {}
_concept = {}
obj = None
clase = None
for i in Invoice.objects.all():
_db[i.invoice] = i
res = {}
for i in ConceptDetail.objects.all():
_concept[i.pk] = i
for i in complex_dictionary:
try:
if int(i['CCLAVE']) in self.clients:
_client = self.clients[int(i['CCLAVE'])]
_client = Client.objects.get(pk=int(i['CCLAVE']))
except:
_client = self._client_default
try:
_date = datetime.date(int(i['FECHA'][0:4]), int(i['FECHA'][4:6]), int(i['FECHA'][6:8]))
except:
_date = datetime.date(1970, 1, 1)
# "Invoice" instance isn't saved in the database.
if i['FACTURA'] in _db:
obj = _db[i['FACTURA']]
else:
try:
obj = Invoice.objects.get(invoice=i['FACTURA'])
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
print('Error getting the Invoice Object:', key, exc_value,
repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
if i['CLVART'] in _concept:
clase = _concept[i['CLVART']]
else:
try:
clase = ConceptDetail.objects.get(pk=i['CLVART'])
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
print('Error getting the ConceptDetail Object:', i['CLVART'], exc_value,
repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
invoice_detail = {
'client': _client,
'date': _date,
'tax': int(i['IVA']),
'concept': clase,
'custom_concept': i['DEART1']+i['DEART2']+i['DEART3']+i['DEART4'],
'amount': i['CANTIDAD'],
'fee': i['HONORARIO'],
'duty': i['DERECHOS'],
'invoice': obj
}
try:
if i[key] in res:
res[i[key]].append(InvoiceDetail.objects.update_or_create(**invoice_detail)[0])
else:
res[i[key]] = [InvoiceDetail.objects.update_or_create(**invoice_detail)[0]]
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
print('Error creating the Invoice Detail:', invoice_detail, exc_value,
repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
def create_invoice_details(self, m):
_invoice_detail = jdft(m.fetch_dbase_table('FACTPAN.DBF')).as_frame('FACTURA')\
.drop(['NOMBRE', 'DESC', 'PRECIO', 'SUBTOT', 'TOIVA', 'RELANEX', 'RFC', 'LASTUP'], 1)\
.to_dict(orient='records')
self._get_invoice_detail('FACTURA', _invoice_detail)