Django的Admin配置

from .models import Food, Menu

from django.contrib import admin


class FoodAdmin(admin.ModelAdmin):
    #显示内容
    list_display = ('foodname', 'company')
    list_filter = ('company',)
    fieldsets = (
        (None, {'fields': ('foodname', 'img', 'score', 'score_times')}),
    )

    #有条件的查询,若为超级用户,则返回全部,否则只返回自己所在部门
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(company=request.user.company)

    # 自动更新,创建时将用户部门自动更新为自己所在部门
    def save_model(self, request, obj, form, change):
        obj.company = request.user.company
        super().save_model(request, obj, form, change)


class MenuAdmin(admin.ModelAdmin):
    #显示内容
    list_display = ('date_time','company')
    list_filter = ('company',)
    fieldsets = (
        (None, {'fields': ('date_time', 'breakfast','lunch','dinner')}),
    )
    filter_horizontal = ('breakfast','lunch','dinner')

    #有条件的查询,若为超级用户,则返回全部,否则只返回自己所在部门
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(company=request.user.company)

    # 自动更新,创建时将用户部门自动更新为自己所在部门
    def save_model(self, request, obj, form, change):
        obj.company = request.user.company
        super().save_model(request, obj, form, change)

    #多对多的列表过滤
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == 'breakfast' or db_field.name =='lunch' or db_field.name =='dinner':
            kwargs["queryset"] = Food.objects.filter(company=request.user.company)
            from django.contrib.admin import widgets
            kwargs['widget'] = widgets.FilteredSelectMultiple(
                db_field.verbose_name,
                db_field.name in self.filter_vertical
            )
        return super(MenuAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)





admin.site.register(Food, FoodAdmin)
admin.site.register(Menu, MenuAdmin)

你可能感兴趣的:(Django的Admin配置)