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

Time:04-25

how do I make it better for the website operator to process the order, can we have each orderitem and shippingaddress associated with the order to be under each "Order" in the admin panel? for example when someone clicks on an Order, he sees the Order data and he's able to scroll and also see the orderitem, and shipping address, would really appreciate your help, 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)

what it looks like rn:

admin.py

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

CodePudding user response:

This would be a solution which works for you

class OrderItemAdmin(admin.StackedInline):
    model = OrderItem

class ShippingAddressAdmin(admin.StackedInline):
    model = ShippingAddress

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

admin.site.register(Order, OrderAdmin)

This is well documented here: https://docs.djangoproject.com/en/stable/ref/contrib/admin/#inlinemodeladmin-objects

  • Related