modelformset_factory foreignkey触发数据库查询

时间:2016-12-21 14:33:40

标签: django

我的模型有一个外键:

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

这是我的(缩写)视图:

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)

这是模板的一部分:

{% 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 %}

显示的每条记录都会触发数据库查询以获取状态说明。

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

你知道为什么或如何阻止这种情况吗?

0 个答案:

没有答案