python - Django REST: serializer field that isn't a model field -
i have 2 models (and matching serializers):
class book(models.model): created = models.datetimefield(auto_now_add=true) owner = models.foreignkey(myuser) title = models.charfield(max_length=100, blank=true, default='') author = models.charfield(max_length=100, blank=true, default='') class readby(models.model): created = models.datetimefield(auto_now_add=true) owner = models.foreignkey(myuser)
when book has been read it's stored in readby database. when user retrieves books using book model/serializer want field telling me if particular user has read book.
i.e. add field model book (pseudo-code):
has_been_read_by = if_exists_in_readby display 'true' else 'false'
so need check if record exists in readby database , display true or false if so.
thanks.
the take away in serializer method of book
model, have access context
provides context['request'].user
, obj
represents book
object
i assume readby
has fk book
, otherwise it's not clear how link them together
class readby(models.model): created = models.datetimefield(auto_now_add=true) owner = models.foreignkey(myuser) book = models.foreignkey(book)
let's make bookserializer
class bookserializer(serializers.modelserializer): class meta: model = book has_been_read_by = serializers.serializermethodfield('get_has_been_read_by') def get_has_been_read_by(self, obj): user = self.context['request'].user book = obj # see if readby object exists return readby.objects.filter(book=book, owner=user).exists()
that field contain either true
or false
, booleans, translated rest format, e.g. json (or can return true
, false
strings easily)
now use in viewset
e.g.
class bookviewset(viewsets.modelviewset): model = book serializer_class = bookserializer
Comments
Post a Comment