问题
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.
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.
I can show object with calling just part: {{ part }}
But I want to be able to call the name of the part, like: {{ part.name }}
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?
Thanks!
回答1:
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()
There's no reason whatsoever to do that. The occasions that you need access to _meta are rare.
来源:https://stackoverflow.com/questions/46319220/call-object-in-template-after-meta-get-fields