-->

Linking to other Foreign Model with DetailView and

2019-07-12 22:51发布

问题:

I am new to django-formset. I have been trying to find a way to link the models at formset (Model_CustomerCart and Model_CustomerCartItem) with the other model named Model_ItemPrice.

Such that with DetailView, the html page can display a list of items and also their corresponding price.

Does anyone know a way to make this happens?

My code is below.

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

Thanks

回答1:

You're already navigating to the Model_ItemIndex via cartitem_.item_name, so from there you should be able to navigate to Model_ItemPrice via model_itempriceset and retrieve the first record.

For example:

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

That would assume though that an item only has one price.