Ad

'RelatedManager' Object Is Not Subscriptable

thanks for your time. i'm trying to get the first images of a foreignKey image model and display with the other fields

i've read some questions and docs about related models and the best i got was to create a function on my models to call it after just to get the first image.

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>

i'm getting the queryset objects although none imaged displayed https://github.com/lucasrf27/dealership

Ad

Answer

It should be:

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

or you can subscript with:

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

You can not subscript the self.images relation itself, you need to use a .all() or .first().

Note that there is a small difference between the two. If there are no related images, then self.images.first() will return None, whereas self.images.all()[0] will raise an error.

Ad
source: stackoverflow.com
Ad