Home > database >  When queryset returned more than one, how choice specific object?
When queryset returned more than one, how choice specific object?

Time:03-13

I try get attribute value item from specific object with queryset below:

x_img = ProductImages.objects.get(product_id=x_id), with that, return more than one, if i use filter, x_img = ProductImages.objects.filter(product_id=x_id), the attribute i need(image_file_w200_png) is unvailable.

The context:

I want to create a dynamic values in my head, to do that my choice is custom context_processors, so:

head_meta_processors.py

import os
from .models import Product, ProductImages
def meta(request):
    path_id = os.path.basename(os.path.normpath(request.path))
    x_id = path_id
    x_obj = Product.objects.get(pk=x_id)
    #...
    # here is the problem
    x_img = ProductImages.objects.get(product_id=x_id)
    x_meta_itemprop_image = x_img.image_file_w200_png.url
    
    return {
        #...
        'meta_itemprop_image': x_meta_itemprop_image,
        #...}

models.py

class Product(models.Model):
    #... some fields

class ProductImages(models.Model):
    #... Fk to model above
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    product_id = ...
    image_type = models.CharField(max_length=33,default='normal')    
    image_file_w200_png = models.ImageField(
        upload_to=upload_to_image_file_w200_png,
        null=True,
        blank=True,
        default='default_image_thumbnail.png'
    )

Each Product model, can have many ProductImages related by product_id field.

So, my queryset, ProductImages.objects.get(product_id=x_id), return 3 objects related with that product_id, how can access each one and how choice a specifc, like a index, e.g.:x_img[0]?

CodePudding user response:

Use .filter(…) and then subscript:

x_img = ProductImages.objects.filter(product_id=x_id)[0]

You can not subscript on a .get(…) since that raises an error when multiple items are returned, hence there is no result to subscript, but a .filter(…) returns a QuerySet that you can subscript.

The above will raise an error in case there is no record to return. You can use .first() [Django-doc] to return None instead:

x_img = ProductImages.objects.filter(product_id=x_id).first()
  • Related