mefe
mefe

Reputation: 317

Filtering two models

I have a problem with following thing: using models described below, I need to search for a car, that has more than x km of mileage and latest visit has date of more than year ago. Of course one car can have more than one visit.

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)

In views.py I have code like this

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})

Unfortunately, it doesn't work. Any ideas?

EDIT Exact code: 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})

Upvotes: 0

Views: 124

Answers (1)

catavaran
catavaran

Reputation: 45595

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

For your real models code should look like this:

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

Upvotes: 1

Related Questions