gpt4 book ai didi

python - 从 Django 模型中过滤外键 ID

转载 作者:太空宇宙 更新时间:2023-11-03 17:55:43 24 4
gpt4 key购买 nike

我想从属于特定 idForiegnkey 中的某些字段获取数据。但我不知道如何让它发挥作用。我有两个模型;

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.')

其他型号

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

尝试上面的代码后我得到了

NameError: name 'tick_id' not defined

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

更新:查看 View

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))

模板

<p> Event Name: {{post.event_name}} </p>

<form action="." method="POST">
{% csrf_token %}

{{BuyTickForm.as_p}}

<input type="submit" class="radbutton radorange" value="Confirm Ticket"/>

</form>

最佳答案

首先,您的模型可以进行一些调整:

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,否则您将返回多个对象,这使用 .get() 时会引发异常。

这个 View 需要一些爱:

def purchase_ticket(request, tikid):
tick = get_object_or_404(Tick, id=tikid)
form = BuyTickForm(request.POST or None, tikid=tikid, user=request.user)

if request.method == 'POST' and form.is_valid():
form.save()
# note that these fields don't exist on your model:
# full_name, phone_no
# return something here... a redirect probably

else:
return render(request, 'buytickform.html',
{'tick': tick, 'form': form})

关于python - 从 Django 模型中过滤外键 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28478600/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com