如何从list_display中的另一个表访问列?

时间:2019-04-29 07:51:52

标签: django django-models django-forms django-views django-admin

我有以下模型:

class Orders(models.Model):
    order_id = models.AutoField(primary_key=True)
    user_id = models.IntegerField()
    status = models.CharField(max_length=100)
    created_at = models.CharField(max_length=100)

    class Meta:
        managed = False
        db_table = 'orders'

class OrderItems(models.Model):
    order_id = models.ForeignKey(Orders, models.DO_NOTHING)
    quantity = models.IntegerField()

    class Meta:
        managed = False
        db_table = 'order_items'

现在假设我希望list_display模型的orders显示列

order_id, user_id, status, created_at, quantity

我知道我可以做这样的事情:

class OrdersAdmin(admin.ModelAdmin):

list_display = ('id', 'user_id', 'status', 'created_at', 'get_quantity')

class Meta:
    model = Orders

def get_quantity(self, obj):
    result = XXX
    return result.get('quantity')

get_quantity.short_description = 'Quantity'

admin.site.register(Order, OrderAdmin)

如何在XXX上访问所需的信息?

1 个答案:

答案 0 :(得分:1)

因此,您需要遵循Orders的反向外键设置(顺便说一句,顺便说一下)。 像这样:

orderitems = obj.orderitems_set.all()
sum = 0
for orderitem in orderitems:
    sum = sum + orderitem.quantity
return sum   

您可以设置related_name重命名反向集:

OrderItems(models.Model):
    order_id = models.ForeignKey(Orders, models.DO_NOTHING, related_name="order_items")

并像order.order_items.all()

那样称呼它

要在OrdersAdmin中订购:

def get_queryset(self,request):
    qs = super(OrdersAdmin,self).get_queryset(request)
    return qs.annotate(get_quantity=Sum('order_items__quantity'))

def get_quantity(self, obj):
    return obj.order_items.all.aggregate(Sum('quantity'))


get_quantity.admin_order_field = 'get_quantity'