3

My model has a foreignkey:

class Status(models.Model):
    status_code = models.CharField(max_length=10, verbose_name="Status Code")
    description = models.CharField(max_length=256, verbose_name="Description")

    def __unicode__(self):
        return "%s - %s" % (self.status_code, self.description)

    def __str__(self):
        return "%s - %s" % (self.status_code, self.description)

class PickUp(models.Model):
    name = models.CharField(max_length=60, verbose_name="Name")
    status = models.ForeignKey(Status, verbose_name="Status", default=None, blank=True, null=True)
    deleted = models.BooleanField(default=False)

    def __unicode__(self):
        return self.name

This is my (abbreviated) view:

def index(request):
    context = dict()

    PickupFormSet = modelformset_factory(PickUp, fields='__all__', form=PickupForm)
    qs = PickUp.objects.filter(deleted=False).prefetch_related('status')

    context['pickupformset'] = PickupFormSet(queryset=qs)

    return render(request, "index.html", context)

This is part of the template:

{% for pickup in pickupformset %}
{% if pickup.id.value %}
<tr>
    <td>{{ pickup.id }}{{pickup.deleted}}</td>
    <td>{{pickup.name}}{{pickup.name.value}}</td>
    <td>{{pickup.status}}</td>
</tr>
{% endif %}
{% endfor %}

Each record displayed triggers a database query to get the status description.

SELECT `frontend_status`.`id`, `frontend_status`.`status_code`, `frontend_status`.`description` FROM `frontend_status`

Do you know why or how I can prevent this?

DDecoene
  • 7,184
  • 7
  • 30
  • 43
  • No, it does not solve this. – DDecoene Dec 21 '16 at 14:58
  • I believe the reason its queried is to construct the forms fields. Not sure how you may fix this though – Sayse Dec 21 '16 at 15:30
  • 1
    See [this question](http://stackoverflow.com/questions/15203207/prevent-django-from-querying-for-foreignkey-options-for-every-form-in-modelforms). In Django 1.9+ I would try overriding [`form_kwargs`](https://docs.djangoproject.com/en/1.10/topics/forms/formsets/#passing-custom-parameters-to-formset-forms) instead of `_construct_forms`. – Alasdair Dec 21 '16 at 15:31
  • I was searching for something like the question you suggested but could not find such. Thank you very much, I will look into what is suggested! – DDecoene Dec 21 '16 at 15:35

0 Answers0