在_meta.get_fields()之后调用模板中的对象 [英] Call object in template after _meta.get_fields()

查看:132
本文介绍了在_meta.get_fields()之后调用模板中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有很多与父模型有关的模型。像这样

So I have lots of models with relations to the parent model. Like this

class Part(models.Model):
    name = models.CharField(max_length=550)

class Stock(models.Model):
    name = models.CharField(max_length=550)

class StockArea(models.Model):
    area = models.CharField(max_length=550)
    stock = models.ManyToManyField(Stock, related_name='stockarea_stock')

class Si(models.Model):
    name = models.CharField(max_length=50)
    si_unit = models.CharField(max_length=10)

class Quantity(models.Model):
    quantity = models.DecimalField(max_digits=10, decimal_places=2)
    si = models.ManyToManyField(Si, related_name='quantity_si')
    part = models.ManyToManyField(Part, related_name='quantity_part')
    stockarea = models.ManyToManyField(StockArea, related_name='quantity_stockarea')

class Image(models.Model):
    image = models.FileField()
    part = models.ManyToManyField(Part, related_name='image_part')

当我想查看零件的详细视图时,我想显示零件名称,数量,图像,股票区域等。

When I want to have a detail view of a part, I want to show Name of part, Quantity, Image, stockarea etc.

因此,对于详细视图,viw看起来像这样

So the viw looks like this for the detail view

def details(request, part_id):
    part = get_object_or_404(Part, pk=part_id)
    part = part._meta.get_fields()
    context = {
        'part': part,
    }
    return render(request, 'part/details.html', context)

尝试调用模板中的所有内容时都会出现问题。

The problem comes when trying to call for everything in the template.

我可以只调用一部分来显示对象: {{part}}

I can show object with calling just part: {{ part }}

但是我希望能够调用该零件的名称,例如: { {part.name}}

But I want to be able to call the name of the part, like: {{ part.name }}

我知道这很麻烦,因为相关字段也称为名称。所以我想我可以这样称呼它: {{part.Part.name}}
或当我想显示数量时: {{part:Quantity.quantity}}

I understand this would be troublesome since related fields also are called 'name'. So I thought I was gonna be able to call it like this: {{ part.Part.name }} or when I want to show quantity: {{ part:Quantity.quantity }}

没有任何工作。所以我的问题是,如何调用对象中的数据?

None is working. So my question is, how do I call the data from the object?

谢谢!

推荐答案

获得的部分对象是一个模型实例。您可以将其用作模型实例。这样就可以了:

The part object you get is a model instance. You can use it as a model instance. So this just works:

{% for image_object in part.image_part.all %}
    <img src="{{ image_object.image.url }}" />
{% endfor %}

也就是说,删除此行后:

That is, after your remove this line:

part = part._meta.get_fields()

没有理由这样做。需要访问_meta的情况很少。

There's no reason whatsoever to do that. The occasions that you need access to _meta are rare.

这篇关于在_meta.get_fields()之后调用模板中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆