如何实施表格来更新数量?我不知道该怎么做。感谢
class Car(models.Model):
name = models.CharField(max_length=50)
price = models.DecimalField()
class GarageCar(models.Model):
car = models.ForeignKey('Car')
garage = models.ForeignKey('Garage')
quantity = models.IntegerField()
class Garage(models.Model):
name = models.CharField("Garage_Name", max_length=30)
cars = models.ManyToManyField('Car', through='GarageCar', blank=True, null=True)
owner = models.ForeignKey(User, related_name='owner_garage', verbose_name='Owner Garage')
以这种方式更新数量:
In [2]: c = Car.objects.get(id=1) #here I need car ID
In [3]: g = Garage.objects.get(owner=1)
In [4]: q = 33 #here I need data from form
In [5]: c= GarageCar.objects.filter(car=c, garage=g).update(quantity=q)
的观点:
def show(request):
user = request.user
garage = Garage.objects.get(owner=user)
return render_to_response('garage.html', {'garage': garage, 'form':form})
在garage.html:
{% for item in garage.garagecar_set.all %}
Car: {{item.car.name}}
Price: {{item.car.price}}
Quantity: {{item.quantity}}
ID: {{item.car.id}}
{% endfor %}
form.py中的:
from django import forms
class QuantityForm(forms.Form):
q = forms.IntegerField
如何创建ORM查询以更新数量?
如何在模板中显示每辆车旁边的表单字段(使用“更新”按钮)?
答案 0 :(得分:1)
看起来你会对FormSets感兴趣,特别是InlineFormSets:
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#using-an-inline-formset-in-a-view
如果你想让它变得非常容易(可能以理解它的工作方式为代价),你可以使用我的通用视图来完全用这个用例。
我的图书馆:https://github.com/AndrewIngram/django-extra-views
则...
views.py:
import extra_views
class EditProductReviewsView(extra_views.InlineFormSetView):
model = Garage
inline_model = GarageCar
fields = ('quantity', )
template_name = 'garage.html'
garage.html:
<form action="." method="post">
{% csrf_token %}
{{ formset.management_form }}
<table>
{% for form in formset %}
<tr>
<td>{{ form.instance.car.name }}</td>
<td>{{ form.instance.car.price }}</td>
{% for field in form.visible_fields %}
<td>
{{ field }}
</td>
{% endfor %}
<div style="display: none;">
{% for field in form.hidden_fields %}{{ field }}{% endfor %}
</div>
<td>{{ form.quantity }}</td>
<td>{{ form.instance.car.id }}</td>
</tr>
{% endfor %}
</table>
<input type="submit" />
</form>
我没有测试过这个例子,我不记得你是否需要将id字段添加到fields
元组中。但基本要点应该是正确的。