Skip to content Skip to sidebar Skip to footer

Django Admin: Inline Straight To Second-level Relationship

I have a three-levels Invoice model which I'd like to display on Django's admin area... in a 'kind of special' way. Allow me to provide a bit of background: Each Invoice is conform

Solution 1:

I think your problem could be solved using the ManyToManyField + through. (This is an example)

#models.pyclassInvoice(models.Model):
    full_total = DecimalField(...)
    # has a .sub_invoices RelatedManager through a backref from SubInvoiceclassSubInvoice(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 InvoiceItemclassInvoiceItem(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 admin
from .models import InvoiceItem, Invoice, SubInvoice


classInvoiceItemInline(admin.TabularInline):
    model = InvoiceItem
    extra = 1classInvoiceAdmin(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.

Post a Comment for "Django Admin: Inline Straight To Second-level Relationship"