1👍
The error you are getting is caused by the fact that you are accessing the image
attribute of a model class, not instance.
The object that is being dehydrated in the dehydrate
method is stored in obj
attribute of the bundle
parameter. Also, you are trying to filter place_image
models to only those with place=1
and cardinality=0
by accessing the image
attribute of place_image
model class. Such filtering won’t work as image
is not a ModelManager
instance. You should use objects
attribute instead. Furthermore, get()
method returns an actual model instance thus a subsequent call to get()
will raise AtributeError
as your place_image
model instances have no attribute get
.
So, all in all, your dehydrate
should look like this:
def dehydrate(self, bundle):
bundle.data['image'] = place_image.objects.get(place_id=1, cardinality=0).image
return bundle
Notice that this code requires the place_image
with desired values to exist, otherwise a place_image.DoesNotExist
will be thrown.
There is also some redundancy in your models:
idPlace
andidImage
can be removed, as django by default creates anAutoField
that is a primary key calledid
when no other primary key fields are definedplace_image.place
field has a redundantto_field
parameter, as by defaultForeignKey
points to a primary key field