从Django模型中过滤ForeignKey id

时间:2015-02-12 13:24:51

标签: python django django-models django-forms

我想从属于特定Foriegnkey的{​​{1}}中的某些字段获取数据。但我可以弄清楚如何让它发挥作用。我有两个模特;

id

另一种模式

class Tick(models.Model):
   user=models.ForeignKey(User)
   event_name=models.CharField(max_length=100)
   ticket_quantity=models.PositiveIntegerField(max_length=50, null=True,  blank=True,help_text='Optional, if you have unlimited ticket')
   ticket_plan_name_a=models.CharField(max_length=100, null=True, blank=True)
   ticket_plan_price_a=models.PositiveIntegerField(max_length=50, null=True, blank=True, verbose_name="Price",help_text='ticket price.')
   ticket_plan_name_b=models.CharField(max_length=100, null=True, blank=True)
   ticket_plan_price_b=models.PositiveIntegerField(max_length=50, null=True, blank=True, verbose_name="Price1",help_text='ticket price.')

在尝试上述代码后,我得到了

  

NameError:名称'tick_id'未定义

如何从模型Tick中获取特定的tick_id,以便在BuyTick表单中显示某些字段?

更新:对于观看次数

class BuyTick(models.Model):
    user=models.ForeignKey(User)
    tik=models.ForeignKey(Tick)
    tiket_qty=models.PositiveIntegerField(max_length=100)
    pub_date=models.DateTimeField()
    full_name=models.CharField(max_length=100)

    def __unicode__(self):
        return self.tiket

class BuyTickForm(forms.ModelForm):
    tik=forms.ModelChoiceField(queryset=Tick.objects.get(pk=tick_id))

    class Meta:
        model=BuyTick

模板

def purchase_ticket(request, tikid):
    if request.method=="POST":
        form=BuyTickForm(request.POST)
        if form.is_valid():
            data=form.cleaned_data
            newbuy=BuyTick(
                user=request.user,
                tik=Ticket.objects.get(pk=tikid),
                tiket_qty=data['tiket_qty'],
                full_name=data['full_name'],
                phone_no=data['phone_no'],
                pub_date=datetime.datetime.now())
            newbuy.save()
            return HttpResponse('Your ticket have been booked')
        else:
            print form.errors
    else:
        return render_to_response('buytickform.html',{'BuyTickForm':BuyTickForm,'post':Tick.objects.all().get(id=tikid)},context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:1)

首先你的模型可以使用一些调整:

class BuyTick(models.Model):
    . . .
    tiket_qty=models.PositiveIntegerField(default=0, max_length=100)
    pub_date=models.DateTimeField(auto_now_add=True)
    . . .

    def __unicode__(self):
        # not sure what you're returning here...
        return self.tiket

您需要在实例化表单时传入id以进行过滤,并且您还可以从请求中传入用户,您可以自动设置该用户:

class BuyTickForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.tikid = kwargs.pop('tikid')
        self.user = kwargs.pop('user')
        super(BuyTickForm, self).__init__(*args, **kwargs)

    tik=forms.ModelChoiceField(queryset=Tick.objects.filter(id=self.tikid))

    class Meta:
        model=BuyTick

    def save(self, commit=True):
        buy_tick = super(BuyTickForm, self).save(commit=False)
        buy_tick.user = self.user
        if commit:
            buy_tick.save()
        return buy_tick

您需要filter() Tick个对象而不是get,否则您将返回多个对象,这会在使用{{1时}}

视图可以使用一些爱:

.get()