如何在Django模板和表单中使用外键?

时间:2019-05-14 09:42:39

标签: python django django-models django-forms

我有一个特殊的表单,可以代表我一个数据列表,但问题是它的运行速度非常慢,表单是否有像django autocomplete_fields这样的东西?

我的表格:

class TripSearchForm(forms.Form):
    departure = forms.ModelChoiceField(queryset=Place.objects.places_for_segment())
    destination = forms.ModelChoiceField(queryset=Place.objects.places_for_segment())
 def places_for_segment(self):
        return Place.objects.filter(Q(role=Place.CITY) | Q(role=Place.VILLAGE) | Q(role=Place.TOWN))

1 个答案:

答案 0 :(得分:0)

第一种方法是,您可以尝试使用select_related预取外键

def places_for_segment(self):
    return Place.objects.filter(
        Q(role=Place.CITY) \
        | Q(role=Place.VILLAGE) \
        | Q(role=Place.TOWN)
     ).select_related('name_of_the_foreign_key', 'another_foreign_key')