簡體   English   中英

如何在django模板和表單中使用外鍵?

[英]How to work with foreign key in django template and 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))

作為第一種方法,您可以嘗試使用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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM