我无法从多个字段访问对象

时间:2019-09-02 01:04:40

标签: python django

我无法访问模板上多对多字段的对象,而我可以访问其他字段的对象

models.py

class Cart(models.Model):
 total = models.IntegerField(max_length=None, default=0)
 timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
 updated = models.DateTimeField(auto_now_add=False, auto_now=True)
 active = models.BooleanField(default=True)
 products = models.ManyToManyField(product)

views.py

def carthome(request):
    cartproduct = Cart.objects.all()
    print(cartproduct)
    context = { 'cartproduct' : cartproduct, }
    return render(request, 'home/carthome.html', context)

在模板中

{% for abc in cartproduct%}
{{ abc.product.name }}
{% endfor %}

错误

AttributeError: 'Cart' object has no attribute 'product'

4 个答案:

答案 0 :(得分:0)

Cart.objects.all()将给您所有Cart。要么遍历模板中的所有模板(尽管我怀疑那是您要执行的操作),要么选择其中一个。

cart = Cart.objects.first()cart = Cart.objects.get(id=1)或任何只给您一辆购物车的物品(因此没有filter())。

然后cartproducts = cart.products.all()应该修复它。排除错字(cartproduct-> cartproduct s ),模板就可以了。


而且,这是一个广泛的话题:您将如何管理购物车中的数量?产品没有数量,而购物车仅容纳产品。除非您使用ForeignKeys cartproductIntegerField数量制作单独的模型,否则您将只能使用单一数量的产品。

答案 1 :(得分:0)

您必须对模型对象和 then 的manytomany字段进行排序-下面提到的选项将起作用。

{% for x in cartproduct %}
{% for y in x.products.all %}
{{ y }}
{% endfor %}
{% endfor %}

答案 2 :(得分:0)

在模型中,您有product = models.ManyToManyField(product)。 确保在产品模型中您具有名称属性。然后尝试这段代码

{% for abc in cartproduct%}
{{ abc.products.name }}
{% endfor %}

似乎在您的代码中,您正在尝试直接建立产品模型。但是您应该先通过Cart(cartproduct)然后添加products(即Cart atribute),然后再命名。

答案 3 :(得分:0)

由于ManyToMany字段可能包含多个项目,因此您需要遍历它们。

例如:

{% for abc in cartproduct %}
{% for product in abc.products.all %}

{{product.name}}

{% if not forloop.last %},{% endif %} # this if condition is to separate the products with comma

{% endfor %}
{% endfor %}