0

我一直在关注 Django 1.4 的通用视图手册,但可以让“出版商列出书籍”示例正常工作。我的网站略有不同,因为我试图按预订该物业的人的姓名(或 ID)列出该物业的预订。人们会多次预订,所以我希望能够查看他们的预订情况。

我的views.url是:

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 个!查找参数为 {}

“获取”是检索数据库中的所有客人,而不是我选择的客人。

我花了几个小时搜索和试验这个,但无济于事。如果我输入“guest = 11”,它会起作用,所以 pk 有问题。

谢谢!

4

1 回答 1

0

你没有给出任何类型的标准来获得客人。实际上,您刚刚说过“给我客人”,而 Django 已经给了您全部 26 个。如果你想按pkkwarg 过滤,你应该这样说:

self.guest =  get_object_or_404(Guest, pk=self.kwargs['pk'])
于 2013-10-06T18:11:46.380 回答