从django中的另一个管理员调用管理员功能

时间:2016-09-30 10:29:33

标签: django django-admin

我有一个products/admin.py如下

# django imports
from django.contrib import admin

# model imports
from products.models import Product
from inventory.models import Inventory


class ProductAdmin(admin.ModelAdmin):
    list_display = # some fields in a tuple
    readonly_fields = # some more fields in a tuple

    def save_model(self, request, obj, form, change):
        if 'is_active' in form.data:
            if form.data['is_active'] == 'on':
                # create an Inventory if product doesn't exists. 
        obj.created_by = request.user
        obj.updated_by = request.user
        if change:
            obj.updated_by = request.user
        obj.save()

admin.site.register(Product, ProductAdmin)

我有一个inventory/admin.py如下

# django imports
from django.contrib import admin

# models imports
from inventory.model import Inventory, DispatchedInventory


class InventoryAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.created_by = request.user
        obj.updated_by = request.user
        if change:
            obj.updated_by = request.user
        obj.save()
    readonly_fields = ['created_by', 'updated_by']

现在,当InventoryAdmin.save_model()为真时,我想在ProductAdmin.save_model()内拨打if form.data['is_active'] == 'on':。 我背后的动机是在产品生效时为产品创建库存。 我知道如何通过采用库存模型本身的实例来创建如下(这将是最后的手段):

inventory_instance = Inventory.objects.get_or_create(product=product)

但是调用管理功能可以完成所有工作,所以我想找到一种方法来实现它。

到目前为止,我所尝试的是将InventoryAdmin作为参数传递:

class ProductAdmin(InventoryAdmin):
    list_display = # some fields in a tuple
    readonly_fields = # some more fields in a tuple
    def save_model(self, request, obj, form, change):
        if 'is_active' in form.data:
            if form.data['is_active'] == 'on':
                # couldn't figure out what to write here. 

任何建议都将不胜感激!提前谢谢。

1 个答案:

答案 0 :(得分:0)

不确定,如果你在这里正确的轨道,但如果你想在管理实例中调用一个方法,你需要做这样的事情:

from django.contrib.admin.sites import AdminSite

adm = InventoryAdmin(Inventory, AdminSite())
inv = Inventory.objects.get_or_create(product=product)
adm.save_model(request, inv, form, change)

不值得努力吗?这是三行代码,InventoryAdmin只有6行

但仔细观察,我认为我可以发现InventoryAdmin中的错误,

obj.updated_by = request.user
if change:
    obj.updated_by = request.user

您正在更新updated_by,无论是否发生了更改,这样另一条线就会被删除!

真的,您在ProductAdmin中需要做的就是

def save_model(self, request, obj, form, change):
    if 'is_active' in form.data:
        if form.data['is_active'] == 'on':
            inv = Inventory.objects.get_or_create(product=obj,
                       created_by=request.user, updated_by=request_user)