2016-10-13 81 views
1

我寫一個應用程序在那裏我有很多家庭在它,只是父親或母親的一個房子是房子的頭:的Django使複雜的查詢集

class House(models.Model): 
    .... 
    def get_head_of_house(self) 
    #searchs in fathers and mothers and find which one is head of house 
    #and returns it 
class Fathers(models.Model): 
    house = models.ForiegnKey(House) 
    first_name = models.CharField() 
    last_name = models.CharField() 
    is_head = models.BooleanField() 
    .... 
class Mothers(models.Model): 
    house = models.ForiegnKey(House) 
    first_name = models.CharField() 
    last_name = models.CharField() 
    is_head = models.BooleanField() 
    .... 

在搜索表單,我得到的第一個名字和房子頭的姓氏。 我想在父親和母親來搜索和選擇所有的房子裏 form.fname在他們FIRST_NAME form.lname是他們的姓氏

問題出在哪裏頭在不同的模型和我關心的頭關於匹配要麼名字姓和更重要查詢集不能手動填充。 如何創建此查詢?

回答

1

您通過創建兩個相同的模型使事情複雜化。

開始通過使基類繼承,如果確實需要

class Parent(models.Model): 
    house = models.ForiegnKey(House) 
    first_name = models.CharField() 
    last_name = models.CharField() 
    is_head = models.BooleanField() 

class Father(Parent): 
    pass 

class Mother(Parent): 
    pass 

然後讓你的查詢從那裏

Parent.objects.filter(is_head=True, Q(first_name=form.fname) | Q(last_name=form.lname)) 

或可能(的房子)

self.parent_set.filter(is_head=True, Q(first_name=form.fname) | Q(last_name=form.lname)) 

沒有你需要的基類幾個查詢

def get_head_of_house(self): 
    fathers = self.fathers_set.filter(is_head=True, Q(first_name=form.fname) | Q(last_name=form.lname)) 
    mothers = self.mothers_set.filter(is_head=True, Q(first_name=form.fname) | Q(last_name=form.lname)) 

    if fathers.exists(): 
     return fathers # or perhaps fathers.first() 

    if mothers.exists(): 
     return mothers # or perhaps mothers.first() 

    return None 
+0

注意:你可以通過查詢父親和母親...我只是認爲這不會是最佳的。 – Sayse

+0

@首先我使用了一個有性別領域的父母課程。孩子有一個母親和一個父親和這是一個錯誤,有兩個外國人父母的孩子模型,所以我把他們分開:) –

+0

@NaserHamidi - 我想象一個孩子和父母之間的ManyToManyField會解決任何問題。雖然有一個基類不會影響你在那裏實現的任何解決方案,因爲你仍然將你的fk保留給父親和母親 – Sayse