我是 django-formset 的新手。我一直在尝试找到一种方法将表单集中的模型(Model_CustomerCart 和 Model_CustomerCartItem)与名为 Model_ItemPrice 的其他模型链接起来。
这样,通过 DetailView,html 页面就可以显示商品列表及其相应的价格。
有谁知道如何实现这一点吗?
我的代码如下。
模型.py
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)
forms.py
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
)
views.py
class View_CustomerCart_DV(DetailView):
queryset = Model_CustomerCart.objects.all()
html
{% 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 %}
谢谢
最佳答案
您已经导航至 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 %}
这假设一件商品只有一个价格。
关于django - 使用 Django 中的 DetailView 和 Formset 链接到其他外部模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50758831/