Error when serializing foreign key model images #8363
Replies: 2 comments 1 reply
-
I manage to track the problem a bit more into the source code: seems that the serialization of the field is maybe not implemented (or I'm using it wrong haha). But please take a look on what I got: rest_framework/fields.py: 1670def to_representation(self, data):
"""
List of object instances -> List of dicts of primitive datatypes.
"""
return [self.child.to_representation(item) if item is not None else None for item in data] As you can see, the function is iterating thought def to_representation(self, data):
"""
List of object instances -> List of dicts of primitive datatypes.
"""
related_manager_type = "<class 'django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager'>"
if str(type(data)) == related_manager_type: # sorry abt the bad type comparison method
data = data.all()
print(data)
return [self.child.to_representation(item) if item is not None else None for item in data] The error disappears, and {
"id": "<pet_id>",
"images": [
null
],
"name": "<name>",
"location": "<location>",
"user": "<user_id>"
} Maybe this is related to the Also: I set |
Beta Was this translation helpful? Give feedback.
-
Ended up doing this way: class PetSerializer(serializers.ModelSerializer):
images = serializers.SerializerMethodField()
class Meta:
model = Pet
fields = "__all__"
extra_kwargs = {
"user": {
"default": serializers.CurrentUserDefault(),
},
}
def get_images(self, pet):
images = PetImage.objects.filter(pet=pet)
urls = []
for image_obj in images:
urls.append(image_obj.image.url)
return urls
def validate(self, data):
request = self.context.get("request")
images = request.FILES.getlist("images")
if len(images) > 0:
data["images"] = images
return data
else:
raise serializers.ValidationError({"images": "You must submit an image."})
def create(self, validated_data):
images = validated_data.pop("images")
pet = Pet.objects.create(**validated_data)
for image in images:
PetImage.objects.create(image=image, pet=pet)
return pet The problem was that I needed to create |
Beta Was this translation helpful? Give feedback.
-
Hey,
I have a model
Pet
and another modelPetImage
, that has a foreign key toPet
. When I'm returning aPet
from the model serializercreate
method, I think that it might be trying to serialize all model'sPetImage
s, but it is having a problem with their manager, since it raises the exception:'RelatedManager' object is not iterable
.I'm not sure if the cause of the problem is right, but please take a look on the serializer code, so I can explain it better:
I think that the error is pretty well explained and tracked, but I'm maybe not deep enought into
DRF
to figure out what's happening after that return statement.Thanks a lot!
Additional resources:
Models Code
View Code
Beta Was this translation helpful? Give feedback.
All reactions