'Sorting and filtering django model objects by foreign key values
so i was given a test for an interview and trying to figure out the best way to implement this:
Lets say we have a django project. With models:
Rental
- name
Reservation
- rental_id
- checkin(date)
- checkout(date)
Add the view with the table of Reservations with "previous reservation ID".
Previous reservation is a reservation that is before the current one into same
rental.

so i tried implementing something that actually works, but i just feel i have ignored alot of good practices just to get the work done, I will appreciate some insights/tips on how i can improve my code, thanks guys. Ps: i really need the job :(
Here is a sample of my code:
##### models
from django.db import models
# Create your models here.
class Rental(models.Model):
name = models.CharField(max_length=100)
def __str__(self) -> str:
return self.name
class Reservations(models.Model):
rental_id = models.ForeignKey(Rental, related_name="rental_id", on_delete=models.CASCADE)
checkin = models.DateField()
checkout = models.DateField()
def __str__(self) -> str:
return f"{self.rental_id.name}, {self.id}"
#### The views implementation
from django.shortcuts import render
from .models import Rental, Reservations
def All_Reservation(request):
reservations = Reservations.objects.all()
rental_names = Rental.objects.values_list('name')
ValueSet = []
for i in sort_by_rental_name(rental_names):
ValueSet += i
mapped = zip(ValueSet,reservations)
print(dict(mapped))
context = {
'reservations': reservations,
'values': ValueSet
}
return render(request, "reservations.html", context)
def sort_by_rental_name(r:any) -> list:
for i in r:
Qset = Reservations.objects.filter(rental_id__name=i[0])
QsetLs = list(Qset)
objects_value_ls = []
for i in QsetLs:
if i.id is min([k.id for k in QsetLs]):
objects_value_ls.append("-")
objects_value_ls.append(QsetLs[QsetLs.index(i)-1].id)
objects_value_ls.remove(objects_value_ls[1])
yield objects_value_ls
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
