2017-09-15 80 views
0

我使用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) 

我想

我想人的所有名稱添加到列表中,無論是選擇直接通過關係,或者一個單位女巫有關係。我怎樣才能做到這一點?

回答

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] 
相關問題