在Django ModelchoiceField中过滤ForeignKey值时出现空白结果

时间:2016-06-13 11:19:28

标签: python django django-models django-views

我有三个型号,他们用作'外键'彼此。

酒店模特

class Hotel(model.Models):
  user= models.ForeignKey(User)
  name= models.CharField(max_length=100, verbose_name='hotel_name')
  address= models.CharField(max_length=100, verbose_name='hotel_address') 
  #more fields

客房模型

class HotelRooms(models.Model):
    hotel= models.ForeignKey(Hotel, related_name='myhotels')
    slug=models.SlugField(max_length=100, unique=True)
    room_name=models.CharField(max_length=100, verbose_name='Room Name')
    #other fields

HotelCalendar模型

class HotelCalendar(models.Model):
    user=models.ForeignKey(User)
    hotel=models.ForeignKey(Hotel)
    hotelrooms=models.ForeignKey(HotelRooms)
     #other fields

现在,我想在HotelCalender表格中显示属于酒店的所有房间,以便所有者选择他/她想要更新和保存的房间。

HotelCalendar表格

class HotelCalendarForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(HotelCalendarForm, self).__init__(*args, **kwargs)
        self.fields['hotelrooms'].queryset=  HotelRooms.objects.filter(hotel=self.instance.hotel_id)

模板

<form id="post_form" method="post" action=""
      enctype="multipart/form-data">

     {% csrf_token %}

     {{  HotelCalendarForm.as_p }}


    <input type="submit" name="submit" value="Submit" />
</form>

浏览

def hotel_calendar_view(request, hotel_id):
    if request.method=="POST":
        form=HotelCalendarForm(request.POST)
        if form.is_valid():
            data=form.cleaned_data
            newbookdate=HotelCalendar(
                user=request.user,
                hotel=Hotel.objects.get(id=hotel_id),
                hotelrooms=data['hotelrooms'],)
            newbookdate.save()
            return render(request, 'notice.html')
            #other code here

当我加载表单时,它不会返回任何值,modelchoicefield只是空白。

我错过了什么?

2 个答案:

答案 0 :(得分:1)

你应该修改一行

self.fields['hotelrooms'].queryset = HotelRooms.objects.filter(hotel=self.instance.hotel_id)

self.fields['hotelrooms'].queryset = HotelRooms.objects.filter(hotel=self.instance.hotel)

当您对外键进行过滤时,它需要一个模型实例。如果你想要过滤外键,你必须这样做:

HotelRooms.objects.filter(hotel_id=self.instance.hotel_id)

如果您想了解更多阅读https://docs.djangoproject.com/ja/1.9/topics/db/queries/#field-lookups

答案 1 :(得分:1)

在GET请求中加载表单时,您似乎正在尝试使用酒店的过滤结果填充hotelrooms字段。如果是这种情况,该字段将不会加载任何数据,因为instance变量将为None

对于初始数据,您需要在GET请求和表单中初始化时将酒店ID传递给表单,使用酒店ID而不是instance.hotel_id加载数据。例如:

views.py

@login_required
def hotel_calendar_view(request, hotel_id):
    if request.method=="POST":
        ## code to post the form data
    else:
        context = {
            'HotelCalendarForm’: HotelCalendarForm(hotel_id=hotel_id),
            'hotel': Hotel.objects.get(id=hotel_id)
        }
        return render(request, 'hotels/hotel_calendar.html', context)
    # return default response

然后在你的表格中:

forms.py

class HotelCalendarForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        hotel_id = kwargs.pop(“hotel_id”, None)
        super(HotelCalendarForm, self).__init__(*args, **kwargs)
        if hotel_id:
            self.fields['hotelrooms'].queryset=HotelRooms.objects.filter(hotel=hotel_id)