“ RelatedManager”对象不可下标

时间:2019-10-21 07:46:46

标签: python django python-3.x django-models django-templates

感谢您的宝贵时间。 我正在尝试获取ForeignKey图像模型的第一张图像并与其他字段一起显示

我已经阅读了有关相关模型的一些问题和文档,而我得到的最好的结果就是在我的模型上创建了一个函数,以在获取第一张图片后调用它。

models.py:

class Veiculos (models.Model):
    YEAR_CHOICES = []
    for r in range(1960, (datetime.now().year+1)):
        YEAR_CHOICES.append((r, r))

    modelo = models.CharField(max_length=100)
    potencia = models.CharField(max_length=40)
    cor = models.CharField(max_length=30)
    preco = models.DecimalField(max_digits=8, decimal_places=2)
    ano = models.IntegerField(('ano'), choices=YEAR_CHOICES, default=datetime.now().year)
    category = models.ManyToManyField('Categorias')
    created_time = models.DateTimeField(auto_now=True)
    updated_time = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s %s' % (self.modelo, self.preco)

    def get_absolute_url(self):
        return reverse('category2')

    def first_image(self):
        return self.images.first()  

def get_image_filename(instance, filename):
    modelo = instance.veicle.modelo
    slug = slugify(modelo)
    return "veiculos_imagens/%s-%s" % (slug, filename)


class Imagens (models.Model):
    veicle = models.ForeignKey(Veiculos, default=None, on_delete=models.CASCADE, related_name='images')
    imagem = models.ImageField(upload_to=get_image_filename)

views.py:

def amp_category(request):
    queryset = Veiculos.objects.all()
    return render(request, 'amp/category.amp.html', {'veiculos': queryset})

category.amp.html:

{% extends "amp/base.amp.html" %} {% block tittle %}
<title>ok</title>{% endblock tittle %} {% block content %}

<body>
    <h1>ok2</h1>
    {% for veiculo in veiculos %}
    <h2>{{veiculo.modelo}}</h2>
    <amp-img src="{{ veiculo.first_image.url }}" alt="ok" width="300" height="340"></amp-img>
    {% endfor %}

</body>

{% endblock %}

</html>

尽管没有图像显示,但我正在获取queryset对象 https://github.com/lucasrf27/dealership

1 个答案:

答案 0 :(得分:2)

应该是:

def first_image(self):
    return self.images.first()

或者您可以使用下标:

def first_image(self):
    return self.images.all()[0]

您无法对self.images关系本身进行下标,需要使用.all().first()

请注意,两者之间的差异很小。如果没有相关图像,则self.images.first()将返回None,而self.images.all()[0]将引发错误。