Django:如何在原始 SQL 查询中使用 django.forms.ModelChoiceField?

标签 django django-forms

我正在尝试使用显示相关实体的组合来呈现表单。因此我使用的是 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/

相关文章:

python - 由于objects.get 查询中的类型转换值而导致 Django 内部服务器错误

python - 如何使用 Django Rest Framework 创建登录 API?

python - 如何指定 Django 表单中字段的顺序?

python - django 中的关系数据库以弹出形式

python - 第三方应用程序的 Django 翻译

python - django中具有多个参数的过滤器和链式过滤器之间的区别

python - Django ModelForm - 使用外键创建实例

django - 以 Django 形式显示全名,而不是用户名

django - 防止 Django 从表单集中保存特定表单

python - Django:ValueError:字段 account.UserProfile.user 引用的模型查找失败:auth.User