как я могу получить между первым и последним изображением продукта, установленным в django restframework - PullRequest
1 голос
/ 31 января 2020

как я могу получить между первым и последним изображением продукта, установленным в django restframework

у меня установлено максимум десять изображений продукта, в моем случае я могу получить первое и последнее изображение продукта набор. Как я могу получить между первым и последним набором изображений продукта. любая помощь, будет признателен.

как я могу получить между первым и последним набором изображений продукта

models.py

class Product(models.Model):
    title = models.CharField(max_length=30)
    slug= models.SlugField(blank=True, null=True)
    sku = models.CharField(max_length=30)
    description = models.TextField(max_length=200, null=True, blank=True)
    instruction = models.TextField(max_length=200, null=True, blank=True)
    price = models.DecimalField(decimal_places=2, max_digits= 10,)
    discount_price= models.DecimalField(decimal_places=2, max_digits= 10, null=True, blank=True)


    category = models.ManyToManyField('Category', )
    default = models.ForeignKey('Category', related_name='default_category', null=True, blank=True, on_delete=models.CASCADE)

    created_on = models.DateTimeField(default=timezone.now)
    updated_on = models.DateTimeField(null=True, blank=True)
    status = models.BooleanField(default=True)


    class Meta:
        ordering = ["-id"]

    def __str__(self): #def __str__(self):
        return self.title 

    def get_absolute_url(self):
        return reverse("product_detail", kwargs={"pk": self.pk})


    def get_first_image_url(self):
        img = self.productimage_set.first()
        if img:
            return img.image.url
        return img #None


def pre_save_post_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = unique_slug_generator(instance)

pre_save.connect(pre_save_post_receiver, sender=Product)


def image_upload_to(instance, filename):
    title = instance.product.title
    slug = slugify(title)
    basename, file_extension = filename.split(".")
    new_filename = "%s-%s.%s" %(slug, instance.id, file_extension)
    return "products/%s/%s" %(slug, new_filename)


class ProductImage(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image = models.ImageField(upload_to=image_upload_to)
    created_on = models.DateTimeField(default=timezone.now)
    status = models.BooleanField(default=True)

    def __unicode__(self):
        return self.product.title

views.py


class ProductUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
   model = Product
   queryset = Product.objects.all()
   serializer_class = DemoAppProductUpdateDestroySerializer
   permission_classes = [IsAdminUser]
   authentication_classes = [BasicAuthentication]

serializers.py

class DemoAppProductUpdateDestroySerializer(serializers.ModelSerializer):

   image = serializers.SerializerMethodField()
   image2 = serializers.SerializerMethodField()
   class Meta:
       model = Product
       fields=[
               "id",
               "title",
               "slug",
               "sku",
               "price",
               "discount_price",
               "image",
               "image2",
       ]

   def get_image(self, obj):
       return obj.productimage_set.first().image.url

   def get_image2(self,obj):
       return obj.productimage_set.last().image.url

Ответы [ 2 ]

1 голос
/ 31 января 2020

Измените ваш сериализатор как,

class DemoAppProductUpdateDestroySerializer(serializers.ModelSerializer):
    <b>images = serializers.SerializerMethodField()</b>

    class Meta:
        model = Product
        fields = [
            "id",
            "title",
            "slug",
            "sku",
            "price",
            "discount_price",
            "images",
        ]

    <b>def get_images(self, obj):
        return [product_image.image.url for product_image in obj.productimage_set.all()]</b>
0 голосов
/ 31 января 2020

Вы можете сделать это в Сериализаторе:

def get_between_images(self,obj):
       images = obj.productimage_set.all().values_list('image', flat=True)

       return images[1:len(images)-1]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...