2015-01-14 90 views
0

我有一個問題,以下事情:使用下面描述的模型,我需要搜索一輛汽車,有超過X公里的里程和最近的訪問有一年多前的日期。當然,一輛車可以有多次訪問。過濾兩個模型

class Car(models.Model): 
    ... 
    id = models.CharField(max_length=10, primary_key=True, db_index=True) 
    mileage = models.PositiveIntegerField(db_index=True) 


class Visit(models.Model): 
    ... 
    id = models.ForeignKey(Car, db_column='id', db_index=False) 
    date = models.DateField(db_index=True) 

在views.py我有這樣

def search_car(request): 
    time_threshold = datetime.now() - timedelta(days=365) 
    cars = Car.objects.filter(mileage__gte=500000, 
    id=Visit.objects.filter(data__lt=time_threshold.date())) 

    return render(request, 'myapp/search_car.html', {'cars': cars}) 

不幸的是代碼,這是行不通的。有任何想法嗎?

編輯精確代碼: models.py

class Samochod(models.Model): 
marka = models.CharField(max_length=30) 
model = models.CharField(max_length=30) 
nr_rejestracyjny = models.CharField(max_length=10, primary_key=True, db_index=True) 
nr_VIN = models.CharField(max_length=17, unique=True, validators=[validators.MinLengthValidator(17)]) 
przebieg = models.PositiveIntegerField(db_index=True) 
id_uzytkownika = models.ForeignKey(User, db_column='id_uzytkownika', db_index=True) 


class Wizyta(models.Model): 
id_wizyty = models.IntegerField(primary_key=True, db_index=True) 
data = models.DateField(db_index=True) 
status = models.CharField(max_length=6, choices=STAN_CHOICE, db_index=True) 
id_uzytkownika = models.ForeignKey(User, db_column='id_uzytkownika', db_index=True) 
nr_rejestracyjny = models.ForeignKey(Samochod, db_column='nr_rejestracyjny', db_index=False) 
przebieg_w_momencie_wizyty = models.PositiveIntegerField() 
opis = models.CharField(max_length=200) 
id_czesci = models.ForeignKey(Czesci, db_column='id_czesci') 
cena = models.PositiveIntegerField() 
czas_pracownikow = models.PositiveIntegerField(validators=[validators.MaxValueValidator(1000)]) 
id_sprzetu = models.ForeignKey(Sprzet, db_column='id_sprzetu', db_index=True) 

views.py

def search_car(request): 
    time_threshold = datetime.now() - timedelta(days=365) 
    samochody = Samochod.objects.distinct().filter(przebieg__gte=500000).exclude(wizyta__date__gte=time_threshold) 

    return render(request, 'warsztat_app/search_car.html', {'samochody': samochody}) 

回答

1
cars = Car.objects.distinct().filter(mileage__gte=500000) \ 
          .exclude(visit__date__gte=time_threshold) 

對於你真正的模型代碼看起來應該是這樣:

samochody = Samochod.objects.distinct().filter(przebieg__gte=500000) \ 
             .exclude(wizyta__data__gte=time_threshold) 
+0

不幸的是,有一個錯誤「關係字段不支持嵌套查找。」 –

+0

你使用哪個版本的django? – catavaran

+0

我的django版本是1.7.1 –