如何通过中间多对多字段查询字段?

时间:2017-09-15 10:28:15

标签: python django django-models django-forms

我使用django 1.8和python 2。

我拥有什么

我有一个类似的模型:

from django.db.models import Model

class Person(Model):
    name = models.CharField()

class Unit(Model):
    unit_name = models.CharField()

class PersonUnitRelType(Model):
    relation=models.CharField()

class PersonUnitRelation(Model):
    person = models.ForeignKey(Person)
    unit = models.ForeignKey(Unit)

我有一个类似的表格:

from django import forms
from ceres.persons.models import Person, PersonUnitRelType, Unit

class MForm(forms.Form):
    persons = forms.ModelMultipleChoiceField(Person.objects)
    units = forms.ModelMultipleChoiceField(Unit.objects)
    relations = forms.ModelMultipleChoiceField(PersonUnitRelType.objects)

我有类似的观点:

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .forms import MessageForm
from ceres.persons.models import Person, PersonUnitRelType, Unit

def messages(request):
    if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
            persons = form.cleaned_data['persons']
            persons_list = [p.name for p in persons]

            relations = form.cleaned_data['relations']
            for relation in relations:
                #TODO: Add all persons in 'relation' to persons_list

            units = form.cleaned_data['units']
            for unit in units:
                #TODO: Add all persons in a unit witch have a 'relation' to persons_list.
            return HttpResponseRedirect("./")
    else:
        form = MForm()

    context = {
        'form': form
    }

    return render(request, 'foo.html', context)

我想要什么

我想将所有人的名字添加到列表中,无论是直接选择,还是通过关系选择,还是由具有关系的单位选择。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

所以这是我添加的代码:

        relations = form.cleaned_data['relations']
        for relation in relations:
            unit_persons = Person.objects.filter(personunitrelation__unit=relation)
            for unit_person in unit_persons:
                persons_list = [p.name for p in persons]

        units = form.cleaned_data['units']
        for unit in units:
            relation_persons = Person.objects.filter(personunitrelation__PersonUnitRelType=relation)
            for relation_person in relation_persons:
                persons_list = [p.name for p in persons]