django-serializer

Django: Nesting serializers in each other

杀马特。学长 韩版系。学妹 提交于 2019-12-12 17:42:00
问题 I'm figuring out how serializers can be merged or nested into each other. In this example I have a column model (consisting of Column class) and data that belong to the column model (consisting of Data class ). My problems is that I don't know how to call ModelSerializer from another serializer class and pass the arguments (the result is always empty). Can you advice me if my model is correct for this situation and how to create the desired JSON so that the result reuses existing serializers

How to dynamically remove fields from serializer output

我怕爱的太早我们不能终老 提交于 2019-12-12 08:18:58
问题 I'm developing an API with Django Rest framework, and I would like to dynamically remove the fields from a serializer. The problem is that I need to remove them depending on the value of another field. How could I do that? I have a serializer like: class DynamicSerliazer(serializers.ModelSerializer): type = serializers.SerializerMethodField() url = serializers.SerializerMethodField() title = serializers.SerializerMethodField() elements = serializers.SerializerMethodField() def __init__(self,

How to paginate queryset for Serializer

寵の児 提交于 2019-12-12 07:07:48
问题 I'm retreiving Category and its outfits list. My problem is there are too many outfits belong to a category . class CategoryListAPIView(generics.RetrieveAPIView): serializer_class = CategoryDetailSerializer ... class CategoryDetailSerializer(serializers.ModelSerializer): outfits = serializers.SerializerMethodField() ... class Meta: model = Category fields = ( ... 'outfits', ... ) def get_outfits(self, obj): //This is returning 39 items. // Can we paginate this? if obj.outfits is not None:

Why does retrieving a single resource execute serializer.to_representation() multiple times in Django REST framework?

喜欢而已 提交于 2019-12-12 04:59:39
问题 Lets say I have a model called Thingy, and there are 20 Thingies in my database. When I retrieve all Thingies, serializer.to_represenatation() is executed 20 times. This is good. However, when I retrieve just a single Thingy from /api/thingies/1, I observe that serializer.to_representation() is executed four (4!!!) times. Why does this happen, and how can I get away with just one call to to_representation()? 回答1: That's because you are using the browsable API. JSON renderer will only call it

How to access Django ForeignKey model field?

≡放荡痞女 提交于 2019-12-12 04:15:33
问题 I have two django models model A class A(models.Model): aname = models.CharField(max_length=64, verbose_name='name') and model B class B(models.Model): bname = models.CharField(max_length=64, verbose_name='name') mod = models.ForeignKey(A, related_name='a_b',null=True,on_delete=models.CASCADE) The serializer for model B is class BSerializer(serializers.ModelSerializer): mod= ASerializer(many=False, read_only=True) class Meta: model = B fields = (','id','bname','mod.aname') I want the aname

Update nested serializer with an overwritten to_representation

荒凉一梦 提交于 2019-12-11 17:36:08
问题 Context So i have an AlbumSerializer with a nested TrackSerializer . For convenience on the frontend I overwrite the representation of AlbumSerializer to make a dictionary of the tracks instead of a list. class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('id', 'order', 'title') # directly upsert tracks def create(self, validated_data): obj, created = Track.objects.update_or_create( album_id= validated_data['album_id'], order=validated_data['order'],

Where to put extra logic in django web API, in the view, or in the serializer?

萝らか妹 提交于 2019-12-11 16:38:26
问题 I have a DRF view which extends CreateModelMixin and GenericViewSet. In the body of the post request, I want to accept an extra field, which does not belong to the related model. Then, I want to pop that extra field, use it for other purposes. I do not want to put that extra field back to the http response because it is a big and complex object. To explain it better here is a sample json input and the response that I want to return to the user: Request: # request { "name": "Why Nations Fail",

Django rest framework errors in trying to persist an image

不羁的心 提交于 2019-12-11 16:34:55
问题 This is my UserProfile object, class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE, ) badge = models.ImageField(upload_to='media/badges/', null=True) reputation = models.IntegerField(default=0) status = models.CharField(max_length=255, null=True, blank=True) thumbnail = models.ImageField(upload_to='media/user/', blank=True, null=True) This is the Serializer, class UserProfileSerializer(serializers.ModelSerializer): thumbnail =

Dynamic nested serializers: empty validated_data

旧巷老猫 提交于 2019-12-11 15:17:15
问题 Hello everyone ! So to start here is the behavior on one of the endpoint, I am working on: # GET Request { "id": 1, "name": "test", "created_date": "date", "completed_date": "date", "template": { "name" : "test" }, => nested serializers with only the field "name" "status": 1, "results": [ { __all__ }, ... ], => nested serializers with all the fields "groups": [ { "name" }, ... ], => nested serializers with only the field "name" } # POST Request { "name": "test", "template": {"name":"test"}, =

Serializer - Django REST Framework - The serializer field might be named incorrectly and not match any attribute or key on the `str` instance

北战南征 提交于 2019-12-11 07:52:17
问题 I want to populate a chartJs exactly like the example: https://www.chartjs.org/docs/latest/charts/bar.html I obtain this error: AttributeError at /timesheet/json-month/ Got AttributeError when attempting to get a value for field `working_hour` on serializer `TimesheetSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'working_hour'. With this model: class Timesheet