Reputation: 83
I want to select items of reservation and sort it by option.effectif where option is declared as FK in table reservation. The sql that I want to have is:
select * from configuration_option, configuration_reservation
where configuration_reservation.option_id= configuration_option.id and valide=True
order by configuration_option.effectif;
For this selection I have tried:
p=Reservation.objects.all().filter(Q(option_id__in=Option.objects.all().order_by('effectif'), valide=True))
The models are:
models
class Reservation( models.Model):
cours=models.ForeignKey(Cours, on_delete=models.CASCADE)
enseignant=models.ForeignKey(Enseignant, on_delete=models.CASCADE)
date_du_jour_reserve=models.DateField("Date du jour reservé")
option=models.ForeignKey(Option,on_delete=models.CASCADE )
valide=models.BooleanField(blank=True, default=False)
class Meta:
ordering=('date_du_jour_reserve')
class Option(models.Model):
code_option=models.CharField("Code de l'option", max_length=6,)
libelle_option= models.CharField("Libélle de l'option", max_length=100)
effectif=models.IntegerField("Effectif", default=0, validators=[
MinValueValidator(limit_value=0 , message=" Attention votre option a un effectif négatif"),
])
def __str__(self):
return self.libelle_option
class Meta:
ordering=('libelle_option',)
Upvotes: 1
Views: 30
Reputation: 476659
You should order the queryset itself. You can .order_by(..)
[Django-doc] on related models by using double underscores (__
):
Reservation.objects.filter(valide=True).order_by('option__effectif')
The filtering here is not necessary on the option
, since an Option
is a ForeignKey
with no null=True
, hence that means that each Reservation
is always pointing to an Option
model.
If you later would allow null=True
, you can filter with:
Reservation.objects.filter(
option__isnull=False,
valide=True
).order_by('option__effectif')
Upvotes: 1