在 Django 中使用 DetailView 和 Formset 链接到其他外国模型

Linking to other Foreign Model with DetailView and Formset in Django

我是 django-formset 的新手。我一直在尝试找到一种方法来 link formset 中的模型(Model_CustomerCart 和 Model_CustomerCartItem)以及另一个名为 Model_ItemPrice.

的模型

使用 DetailView,html 页面可以显示项目列表及其相应的价格。

有谁知道实现这一目标的方法吗?

我的代码如下。

models.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 %}

谢谢

您已经通过 cartitem_.item_name 导航到 Model_ItemIndex,因此从那里您应该能够通过 model_itempriceset 导航到 Model_ItemPrice 并检索第一条记录.

例如:

{% for cartitem_ in object.model_customercartitem_set.all %}
    {{ cartitem_.item_name }} 
    {{ cartitem_.item_name.model_itemprice_set.first.item_price}}
{% endfor %}

这是假设一件商品只有一个价格。