我一直在关注Django 1.4的通用视图手册,但可以通过“发布商列表”示例来实现。我的网站略有不同,因为我试图通过预订酒店的人的姓名(或身份证)来列出房产的预订。人们会不止一次预订,所以我希望能够看到他们的预订。
我的观点。这是:
class GuestBookingListView(DetailView):
context_object_name = 'guest_booking'
template_name = 'guest_booking.html'
def get_queryset(self):
self.guest = get_object_or_404(Guest)
return Booking.objects.filter(guest = self.guest)
def get_context_data(self, **kwargs):
context = super(GuestBookingListView, self).get_context_data(**kwargs)
context['guest'] = self.guest
return context
我的模特是:
class Guest(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=50)
spouse_first = models.CharField(max_length=30, blank=True)
spouse_last = models.CharField(max_length=50, blank=True)
num_child = models.IntegerField(verbose_name='Number of children')
address = models.TextField(max_length=50, blank=True)
city = models.CharField(max_length=60, blank=True, verbose_name='Town / City')
state_province = models.CharField(max_length=30, blank=True, verbose_name='County')
post_code = models.CharField(max_length=8, blank=True)
country = models.CharField(max_length=50, blank=True)
email = models.EmailField(blank=True)
landline = models.CharField(max_length=25, blank=True)
mobile = models.CharField(max_length=25, blank=True)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
class Booking(models.Model):
guest = models.ForeignKey(Guest)
ack_date = models.DateField(verbose_name='Date acknowledged')
start_date = models.DateField(verbose_name='Start date')
end_date = models.DateField(verbose_name='End date')
dep_recd = models.DateField(null=True, blank=True, verbose_name='Deposit received')
bal_recd = models.DateField(null=True, blank=True, verbose_name='Balance received')
keys_sent = models.DateField(null=True, blank=True, verbose_name='Date keys sent')
sec_retn = models.DateField(null=True, blank=True, verbose_name='Security deposit returned')
rtm_sent = models.IntegerField('Status', blank=True)
notes = models.TextField(blank=True, verbose_name='Notes')
和我的urls.py是:
url(r'^guests/(?P<pk>\d+)/$', GuestBookingListView.as_view (
#context_object_name = 'booking_list',
)),
到目前为止,我可以看到这个示例相同(使用不同的字段名称),但我得到的结果是:
get()返回多个Guest - 它返回26!查找参数为{}
'get'正在检索数据库中的所有Guest,而不是我选择的那个。
我花了几个小时搜索和试验这个,但无济于事。如果我把'guest = 11'设置为有效,那么pk就有问题了。
谢谢!
答案 0 :(得分:0)
您没有给出任何标准来接待客人。你刚刚说过,“给我客人”,Django给了你所有26个。如果你想按pk
kwarg过滤,你应该这样说:
self.guest = get_object_or_404(Guest, pk=self.kwargs['pk'])