Django admin: Inline straight to second-level relationship

寵の児 提交于 2019-12-03 07:24:51

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

#models.py
class Invoice(models.Model):
    full_total = DecimalField(...)
    # has a .sub_invoices RelatedManager through a backref from SubInvoice

class 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 InvoiceItem

class InvoiceItem(models.Model):
    sub_invoice = ForeignKey('server.SubInvoice')
    invoice = ForeignKey('server.Invoice')
    product = ForeignKey('server.Product', related_name='+')
    quantity = PositiveIntegerField(...)
    price = DecimalField(...)

#admin.py
from django.contrib import admin
from .models import InvoiceItem, Invoice, SubInvoice


class InvoiceItemInline(admin.TabularInline):
    model = InvoiceItem
    extra = 1


class 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!