我将从展示模型的外观开始:
from django.db import models
class Project(models.Model):
#.....
pu = models.ForeignKey('Person', default='', related_name='pu')
se = models.ForeignKey('Person', default='', related_name='se')
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
department = models.ForeignKey('Department', default='')
class Department(models.Model):
abbreviation = models.CharField(default='', max_length=3)
full_name = models.CharField(default='', max_length=20)
我想将所有人保留在一个表格中,但在我的管理面板中,我想显示两个单独的过滤列表:
我搜索了很多,但我对django和Python都很新。
我怎样才能实现它?
答案 0 :(得分:0)
尝试创建myapp / admin.py文件
from django.contrib import admin
from .models import Project, Person
class ProjectAdmin(admin.ModelAdmin):
...
filter_horizontal = ('pu', 'se')
def get_form(self, request, obj=None, **kwargs):
form = super(ProjectAdmin, self).get_form(request, obj, **kwargs)
if obj:
form.base_fields['pu'].queryset = Person.objects.filter(department__abbreviation__startswith='pu')
form.base_fields['se'].queryset = Person.objects.filter(department__abbreviation__startswith='se')
return form
admin.site.register(Project, ProjectAdmin) # register it
答案 1 :(得分:0)
我改变了我的模特。 我不会使用人员和部门,我已切换到django的用户和组。
要根据我的需要过滤它,我使用了limit_choices_to
。
pu = models.ForeignKey("auth.User", related_name='pu', limit_choices_to={'groups__name': "Purchasing"})
se = models.ForeignKey("auth.User", related_name='se', limit_choices_to={'groups__name': "Sales"})
我基于这个答案:Django, filter users by group in a model foreign key