Home > Software engineering >  Django: Access model field with two keys in template
Django: Access model field with two keys in template

Time:12-02

I am a bit lost. It is been a while since I did some Django and I almost forgot everything about querysets and template. The app is a questionaire for comparing different vendors - hence their products. It is a questionaire with a scoring (best match) to each product.

I want to access a specific element in a for loop which has two foreign keys to other classes. Here my model:

Model:

class Question(models.Model):
    questionText = models.CharField(max_length=500)

class Vendor(models.Model):
    vendorName = models.CharField(max_length=30, unique=True)

class Scoring(models.Model):        
    score = models.IntegerField(default='0', blank=True)
    questionScoreForKey = models.ForeignKey(Question, null=True, related_name='scorequestion', on_delete=models.SET_NULL)
    vendorForKey = models.ForeignKey(Vendor, null=True, related_name='scorevendor', on_delete=models.SET_NULL)

views.py

def index(request):
    questions = Question.objects.all()
    vendors = Vendor.objects.all()
    return render(request, 'compare/index.html', {'questions': questions, 'vendors': vendors})

Template

{% for ask in questions %}
<tr>
  <td>{{ ask.questionText }}  </td>
    {% for vend in vendors %}
    <td id="Vendor_{{ ask.pk }}_{{ vend.pk }}" style> {{ HERE THE SCORE OF THE QUESTION AND VENDOR  }}  </td> 
    {% endfor %}
</tr>
{% endfor %}

Both keys are existing but I have no clue how to access the score of e. g. the first question for the first vendors. Any hint appreciated.

CodePudding user response:

You need to reverse query the scores. Since you've defined related names in your models, you can use them.

Note that a reverse query gives you a manager object. The all method returns a queryset with all objects matching the reverse query (you defined a one-to-many relationship, one question/vendor can have many scores). Then further filter the queryset to get the instance you need (e.g. first).

{{vendor.scorevendor.all.first.score}}
  • Related