Include part image URL in Part API

This commit is contained in:
Oliver Walters 2019-05-08 15:25:28 +10:00
parent 6a04e8b059
commit 416b5c9820
2 changed files with 14 additions and 0 deletions

View File

@ -14,6 +14,7 @@ import tablib
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.conf import settings
from django.db import models
from django.core.validators import MinValueValidator
@ -120,8 +121,17 @@ class Part(models.Model):
"""
def get_absolute_url(self):
""" Return the web URL for viewing this part """
return reverse('part-detail', kwargs={'pk': self.id})
def get_image_url(self):
""" Return the URL of the image for this part """
if self.image:
return os.path.join(settings.MEDIA_URL, str(self.image.url))
else:
return ''
# Short name of the part
name = models.CharField(max_length=100, unique=True, blank=False, help_text='Part name (must be unique)')

View File

@ -33,6 +33,7 @@ class PartBriefSerializer(serializers.ModelSerializer):
""" Serializer for Part (brief detail) """
url = serializers.CharField(source='get_absolute_url', read_only=True)
image_url = serializers.CharField(source='get_image_url', read_only=True)
class Meta:
model = Part
@ -40,6 +41,7 @@ class PartBriefSerializer(serializers.ModelSerializer):
'pk',
'url',
'name',
'image_url',
'description',
'available_stock',
]
@ -51,6 +53,7 @@ class PartSerializer(serializers.ModelSerializer):
"""
url = serializers.CharField(source='get_absolute_url', read_only=True)
image_url = serializers.CharField(source='get_image_url', read_only=True)
category_name = serializers.CharField(source='category_path', read_only=True)
class Meta:
@ -60,6 +63,7 @@ class PartSerializer(serializers.ModelSerializer):
'pk',
'url', # Link to the part detail page
'name',
'image_url',
'IPN',
'URL', # Link to an external URL (optional)
'description',