django - 使用 Django 中的 DetailView 和 Formset 链接到其他外部模型

标签 django inline-formset

我是 django-formset 的新手。我一直在尝试找到一种方法将表单集中的模型(Model_CustomerCart 和 Model_CustomerCartItem)与名为 Model_ItemPrice 的其他模型链接起来。

enter image description here

这样,通过 DetailView,html 页面就可以显示商品列表及其相应的价格。

enter image description here

有谁知道如何实现这一点吗?

我的代码如下。

模型.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/

相关文章:

django - django.contrib.auth.User在Django源代码中定义在哪里

python - 谷歌应用引擎上的 webapp、tipfy 或 django

python - Django嵌套表单集动态添加表单

python - Django 内联表单集和选择字段生成过多的数据库查询

python - 使用干净的更改 Django 表单集中的字段

python - Django 内联表单集将始终创建新对象而不是更新它们

python - 不区分大小写的翻译

python - Django 管理表单字段 - 在选择框中显示对象相关的查询结果

python - 表单集、外键和 OneToOne

django - 易于使用的 django 验证码或带有验证码的注册应用程序?