I am looking to add Images, to a Listing(ForeignKey), which will already be in my database.
I have an Image model..
class Image(models.Model):
photo = models.ImageField(blank=True, upload_to=get_image_filename)
listing = models.ForeignKey(Listing, on_delete=models.CASCADE)
ImageSerializer
class ImageSerializer(serializers.HyperlinkedModelSerializer):
photo = serializers.ImageField(allow_empty_file=True)
class Meta:
model = Image
fields = ('url', 'photo', 'listing', )
def create(self, data):
listing, __ = Listing.objects.get_or_create(listing=data["listing"])
return Image(photo=data["photo"], listing=listing)
ImageViewSet
class ImageViewSet(viewsets.ModelViewSet):
queryset = Image.objects.all()
serializer_class = ImageSerializer
detail_serializer_class = ImageDetailSerializer
parser_classes = (FormParser, MultiPartParser)
'''Show detailed Image view'''
def get_serializer_class(self):
if self.action == 'retrieve':
if hasattr(self, 'detail_serializer_class'):
return self.detail_serializer_class
return super(ImageViewSet, self).get_serializer_class()
I have tried overriding the create method in the serializer, and perform_create method in the actual viewset. But keep running into errors. Any advice in the right direction would be awesome]1
FieldError at /api/v1/images/
Cannot resolve keyword 'listing' into field. Choices are: address, airconditioning, amenities, approximate_square_footage, basement, city, community, description, exteriorhouse, garages, heating, hoa, house_levels, id, image, latitude, listprice, longitude, lot_size, numberbedrooms, numberfullbaths, numberhalfbaths, outbuildings, propertyviews, pub_date, roof_type, roomtotal, schools, style_house, taxes, taxmap, type_house, unfinished_square_footage, user, user_id, water, yearbuilt, zipcode, zoning
Edit
changed create method to...
def create(self, validated_data):
listing_data = validated_data.pop('listing')
image = Image.objects.create(**validated_data)
image.listing =Listing.objects.get(photo=image,
listing_data=listing_data)
return image
Now the error...
save() got an unexpected keyword argument 'force_insert'