DJANGO: как ограничить набор запросов inlineformset - PullRequest
5 голосов
/ 15 марта 2012

ЕС может использовать эту форму для выбора ролей (руководитель проекта, разработчик и т. Д.), Которые они играют для любого данного проекта. Я хочу ограничить параметры поля проекта только теми, которые находятся в отделе сотрудников. Прямо сейчас, ЕС может выбрать проект любого департамента (но не департамент, я это полностью исключил). Как я могу это сделать? queryset = blabla не работает ..

МОДЕЛЬ:

class Department(models.Model):
    name = models.CharField(max_length=20)
    def __unicode__(self):
        return self.name

class Employee(models.Model):
    fname = models.CharField(max_length=15)
    department = models.ForeignKey(Department)
    def __unicode__(self):
        return self.fname

class Projecttype(models.Model):
    name = models.CharField(max_length=20)
    def __unicode__(self):
        return self.name

class Project(models.Model):
    projecttype = models.ForeignKey(Projecttype)
    department = models.ForeignKey(Department)
    members = models.ManyToManyField(Employee, through='Membership')
    def __unicode__(self):
       return "%s > %s" % (self.department, self.projecttype)

class Role(models.Model):
    name = models.CharField(max_length=20)
    def __unicode__(self):
       return self.name

class Membership(models.Model):
    project = models.ForeignKey(Project, null=True)
    department = models.ForeignKey(Department)
    employee = models.ForeignKey(Employee)
    role = models.ManyToManyField(Role, blank=True, null=True)
    class Meta:
        unique_together = (("project", "employee",),)

ВИД:

def employee_edit(request, employee_id):
    i = get_object_or_404(Employee, pk=employee_id)
    EmployeeInlineFormSet = inlineformset_factory(Employee, Membership, extra=1, exclude=('department',), queryset=Membership.objects.filter(department=i.department))
    if request.method == "POST":
        f = EmployeeInlineFormSet(request.POST, instance=i)
        if f.is_valid():
            f.save()
    else:
        f = EmployeeInlineFormSet(instance=i)
    return render_to_response('testdb/edit.html', {'item': i, 'formset': f, }, context_instance=RequestContext(request))

JSON: MANAGE.PY DUMPDATA TESTDB --INDENT = 4

[
    {
        "pk": 1,
        "model": "testdb.department",
        "fields": {
            "name": "IT Department"
        }
    },
    {
         "pk": 2,
        "model": "testdb.department",
        "fields": {
            "name": "Operations Department"
        }
    },
    {
        "pk": 1,
        "model": "testdb.employee",
        "fields": {
            “department”: 1,
            "fname": "Alice"
        }
    },
    {
        "pk": 2,
        "model": "testdb.employee",
        "fields": {
            “department”: 2,
            "fname": "Eve"
        }
    },
    {
        "pk": 3,
        "model": "testdb.employee",
        "fields": {
            “department”: 1,
            "fname": "Bob"
        }
    },
    {
        "pk": 1,
        "model": "testdb.projecttype",
        "fields": {
            "name": "PROCESS IMPROVEMENT"
        }
    },
    {
        "pk": 2,
        "model": "testdb.projecttype",
        "fields": {
            "name": "DATA CLEANUP"
        }
    },
    {
        "pk": 1,
        "model": "testdb.project",
        "fields": {
            “projecttype”: 1,
            “department”: 1
        }
    },
    {
        "pk": 2,
        "model": "testdb.project",
        "fields": {
            “projecttype”: 1,
            “department”: 2
        }
    },
    {
        "pk": 3,
        "model": "testdb.project",
        "fields": {
            “projecttype”: 2,
            “department”: 1
        }
    },
    {
        "pk": 1,
        "model": "testdb.role",
        "fields": {
            "name": "Project Manager"
        }
    },
    {
        "pk": 2,
        "model": "testdb.role",
        "fields": {
            "name": "Analyst"
        }
    },
    {
        "pk": 1,
        "model": "testdb.membership",
        "fields": {
            "employee": 1,
            “department”: 1,
            “project”: 1,
            "role": [
                1,
                2
            ]
        }
    },
    {
        "pk": 2,
        "model": "testdb.membership",
        "fields": {
            "employee": 2,
            “department”: 2,
            “project”: 2,
            "role": [
                1
            ]
        }
    },
    {
        "pk": 3,
        "model": "testdb.membership",
        "fields": {
            "employee": 3,
            “department”: 1,
            “project”: 1,
            "role": [
                1
            ]
        }
    }
]

1 Ответ

8 голосов
/ 15 марта 2012

На этом этапе вы создаете класс formset, не передавайте здесь набор запросов:

EmployeeInlineFormSet = inlineformset_factory(Employee, Membership, extra=1, exclude=('department',))

Передайте набор запросов при создании экземпляра formsete:

f = EmployeeInlineFormSet(instance=i, queryset=Membership.objects.filter(department=i.department))

например:

def employee_edit(request, employee_id):
    i = get_object_or_404(Employee, pk=employee_id)
    queryset=Membership.objects.filter(department=i.department)
    EmployeeInlineFormSet = inlineformset_factory(Employee, Membership, extra=1, exclude=('department',))
    if request.method == "POST":
        f = EmployeeInlineFormSet(request.POST, instance=i, queryset=queryset)
        if f.is_valid():
            f.save()
    else:
        f = EmployeeInlineFormSet(instance=i, queryset=queryset)
    return render_to_response('testdb/edit.html', {'item': i, 'formset': f, }, context_instance=RequestContext(request))
...