如何将关联模型直接链接到管理面板中的 ModelAdmin?

How to have associated models to be directly linked to a ModelAdmin in the admin panel?

如何让网站运营商更好地处理订单,我们能否将与订单关联的每个订单项和送货地址都放在管理面板中的每个“订单”下?例如,当有人点击订单时,他会看到订单数据,并且能够滚动并看到订单项和送货地址,非常感谢您的帮助,thx!

models.py

class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
    date_ordered = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False)
    transaction_id = models.CharField(max_length=100, null=True)


class OrderItem(models.Model):
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
    quantity = models.IntegerField(default=0)
    date_added = models.DateTimeField(auto_now_add=True)

    status = models.CharField(max_length=40, choices=STATUS_CHOICES, default="Order Placed")
    tracking_no = models.CharField(max_length=300, null=True, blank=True)



class ShippingAddress(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
    address_one = models.CharField(max_length=200)
    city = models.CharField(max_length=200)
    country = models.CharField(max_length=300)
    zipcode = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

它看起来像什么 rn:

admin.py

admin.site.register(Order, OrderAdmin)
admin.site.register(OrderItem, OrderItemAdmin)
admin.site.register(ShippingAddress, ShippingAddressAdmin)

这将是适合您的解决方案

class OrderItemAdmin(admin.StackedInline):
    model = OrderItem

class ShippingAddressAdmin(admin.StackedInline):
    model = ShippingAddress

class OrderAdmin(admin.ModelAdmin):
    inlines = [OrderItemAdmin, ShippingAddressAdmin]

admin.site.register(Order, OrderAdmin)

这在此处有详细记录:https://docs.djangoproject.com/en/stable/ref/contrib/admin/#inlinemodeladmin-objects