我正在尝试使用显示相关实体的组合来呈现表单。因此我使用的是 ModelChoiceField。
这种方法效果很好,直到我需要限制要显示的实体。如果我使用简单的查询表达式,它也可以很好地工作,但是如果我使用原始 SQL 查询,事情就会中断。
所以我的代码有效,将查询集设置为过滤器表达式。
class ReservationForm(forms.Form):
location_time_slot = ModelChoiceField(queryset=LocationTimeSlot.objects.all(), empty_label="Select your prefered time")
def __init__(self,*args,**kwargs):
city_id = kwargs.pop("city_id") # client is the parameter passed from views.py
super(ReservationForm, self).__init__(*args,**kwargs)
# TODO: move this to a manager
self.fields['location_time_slot'].queryset = LocationTimeSlot.objects.filter(city__id = city_id )
但是,如果我将其更改为原始查询,我就会开始遇到问题。不起作用的代码:
class ReservationForm(forms.Form):
location_time_slot = ModelChoiceField(queryset=LocationTimeSlot.objects.all(), empty_label="Select your prefered time")
def __init__(self,*args,**kwargs):
city_id = kwargs.pop("city_id") # client is the parameter passed from views.py
super(ReservationForm, self).__init__(*args,**kwargs)
# TODO: move this to a manager
query = """SELECT ts.id, ts.datetime_to, ts.datetime_from, ts.available_reserves, l.name, l.'order'
FROM reservations_locationtimeslot AS ts
INNER JOIN reservations_location AS l ON l.id = ts.location_id
WHERE l.city_id = %s
AND ts.available_reserves > 0
AND ts.datetime_from > datetime() """
time_slots = LocationTimeSlot.objects.raw(query, [city_id])
self.fields['location_time_slot'].queryset = time_slots
尝试呈现小部件时遇到的第一个错误是:“RawQuerySet”对象没有属性“all”
感谢 enter link description here 中的一位 cometd ,我可以解决这个问题, 通过做:
time_slots.all = time_slots.__iter__ # Dummy fix to allow default form rendering with raw SQL
但是现在我在发布表单时得到了类似的信息:
'RawQuerySet' 对象没有属性 'get'
是否有正确的方法来准备供 ModelChoiceField 使用的 RawQuerySet?
谢谢!
最佳答案
你确定你真的需要一个原始查询吗?看看那个查询,我看不出有什么理由不能用 filter(location__city=city_id, available_reserves__gte=0, datetime_from__gt=datetime.datetime.now())
来做。 .
原始查询集缺少在传统查询集上定义的许多方法,因此如果不为所有这些方法编写自己的定义,就不可能将它们放在适当的位置。
关于Django:如何在原始 SQL 查询中使用 django.forms.ModelChoiceField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17330158/