Django admin: Inline straight to second-level relationship
I think your problem could be solved using the ManyToManyField
+ through
. (This is an example)
#models.pyclass Invoice(models.Model): full_total = DecimalField(...) # has a .sub_invoices RelatedManager through a backref from SubInvoiceclass SubInvoice(models.Model): sub_total = DecimalField(...) invoice = ManyToManyField( 'server.Invoice', through='server.InvoiceItem', through_fields=('sub_invoice', 'invoice')) # has an .items RelatedManager through a backref from InvoiceItemclass InvoiceItem(models.Model): sub_invoice = ForeignKey('server.SubInvoice') invoice = ForeignKey('server.Invoice') product = ForeignKey('server.Product', related_name='+') quantity = PositiveIntegerField(...) price = DecimalField(...)#admin.pyfrom django.contrib import adminfrom .models import InvoiceItem, Invoice, SubInvoiceclass InvoiceItemInline(admin.TabularInline): model = InvoiceItem extra = 1class InvoiceAdmin(admin.ModelAdmin): inlines = (InvoiceItemInline,)admin.site.register(Invoice, InvoiceAdmin)admin.site.register(SubInvoice, InvoiceAdmin)
I would recommend working with classes for this one in your views.py
and use inlineformset_factory
in your forms.py
for this.Using jquery-formset
library in your frontend as well, as this looks pretty neat together.
NOTE:You can also use on_delete=models.CASCADE
if you want in the InvoiceItem
on the foreignkeys, so if one of those items is deleted, then the InvoiceItem will be deleted too, or models.SET_NULL
, whichever you prefer.
Hope this might help you out.