jeudi 30 mars 2017

django - Find max using two foreign keys, and using __in

I am pretty new on Django and Python and I have a problem. Here are my models :

class Similarity(models.Model):
    score = models.FloatField(max_length=10) 
    mother_fk = models.ForeignKey('MotherCompound', on_delete=models.CASCADE)
    father_fk= models.ForeignKey('FatherCompound',on_delete=models.CASCADE)

Using this view (only the important part) :

mothers =XXXXX_set.all() #queryset of mothers
fathers =XXXXX_set.all() #queryset of fathers

couple= Similarity.objects.filter(mother_fk__in=mothers,father_fk__in=fathers)

At the end, I will have a table of this shape, different combinations between these two foreign keys.

  • M1/F1 = 1.0
  • M1/F2 = 0.9
  • M2/F1 = 0.6
  • M3/F1 = 0.5
  • M2/F3 = 0.3
  • M3/F2 = 0.1

I want depending of the min(len(mothers),len(fathers))( let's say "3") to obtain three couple of Mother/Father with this filter :

You look for the best score where a mother and a father is involved in.

I mean, a mother and a father can be involved on different combination, but I want to display only one example of them based on the best score.

On this example, final output should be :

  • M1/F1 = 1.0
  • M2/F3 = 0.3
  • M3/F2 = 0.1

My question is, is it possible to make it in one line, within the query, or if after the query line , I have to make a loop and try to find the max for each mothers and fathers. In both case, I would like to have am example to follow because I am struggling since days on this problem.

I hope it will be clear, if not , do not hesitate to ask me more details. Thank you.




Aucun commentaire:

Enregistrer un commentaire