我是django-formset的新手。我一直试图找到一种方法将formset(Model_CustomerCart和Model_CustomerCartItem)的模型与名为Model_ItemPrice的其他模型链接起来。
使用DetailView,html页面可以显示项目列表以及相应的价格。
有没有人知道如何实现这一目标?
我的代码如下。
class Model_ItemIndex(models.Model):
item_name = models.CharField(max_length = 50, null = True, blank = False)
class Model_ItemPrice(models.Model):
item_name = models.ForeignKey(Model_ItemIndex, null = True, blank = False)
item_price = models.FloatField(null = True, blank = False)
class Model_CustomerCart(models.Model):
customer_name = models.CharField(max_length = 50, null = True, blank = False)
class Model_CustomerCartItem(models.Model):
customer_name = models.ForeignKey(Model_CustomerCart)
item_name = models.ForeignKey(Model_ItemIndex)
class Form_ItemIndex(forms.ModelForm):
class Meta:
model = Model_ItemIndex
fields = [
"item_name",
]
class Form_ItemName(forms.ModelForm):
class Meta:
model = Model_ItemName
fields = [
"item_name",
"item_price",
]
class Form_CustomerCart(forms.ModelForm):
class Meta:
model = Model_CustomerCart
fields = [
"customer_name",
]
class Form_CustomerCartItem(forms.ModelForm):
class Meta:
model = Model_CustomerCartItem
fields = [
"customer_name",
"item_name",
]
Formset_customercartitem = forms.inlineformset_factory(
Model_CustomerCart,
Model_CustomerCartItem,
form = Form_CustomerCartItem,
extra = 3
)
class View_CustomerCart_DV(DetailView):
queryset = Model_CustomerCart.objects.all()
{% for cartitem_ in object.model_customercartitem_set.all %}
{{ cartitem_.item_name }}
{{ cartitem_.item_name.item_price }} <------ How can I get the item_price from Model_ItemPrice?
{% endfor %}
由于
答案 0 :(得分:1)
您已经通过Model_ItemIndex
导航到cartitem_.item_name
,因此您应该可以通过Model_ItemPrice
导航到model_itempriceset
并检索第一条记录。
例如:
{% for cartitem_ in object.model_customercartitem_set.all %}
{{ cartitem_.item_name }}
{{ cartitem_.item_name.model_itemprice_set.first.item_price}}
{% endfor %}
虽然一件物品只有一个价格,但我们会假设。