python - How to serialize models in Django? -


I have a very simple and clear question that I am trying to search for some time.

I have a model, image , which has foreign code like is created , province , and City .

I want to sort all the model areas on json which I need. Models.py:

  class pictures (models.Model): name = models.TextField ("title", MAX_LENGTH = 10000, null = true, empty = true) meta_data = models.TextField ( "Meta_data", null = true, empty = true) created_by = models.ForeignKey (user, related_name = "created_by") city = models.ForeignKey (city, null = true, empty = true) pro = models.ForeignKey (province, Verbose_name = "province") class province (models.Model): name = models.CharField (MAX_LENGTH = 50) pi_meta_data = models.TextField (zero = true, empty = true) intro = models.CharField (MAX_LENGTH = 1000, null = True, empty = true) description = models.TextField (max_length = 10000, tap = true, empty = true) square city (model S.Model): name = models.CharField (max_length = 50) pi_meta_data = mode ls.TextField (Zero = true, empty = true) Introduction = models.CharField (MAX_LENGTH = 1000, Null = true, empty = true) Description = Models.TextField (MAX_LENGTH = 10000, Null = true, empty = true)  

You can use, and easily model.

Your model will be serial:

  class Illustrator (serializers.ModelSerializer): Square Meta: Model = Picture # In this case, the field is only to show that the picture Each field is serialized in the model Serializes field # will be left out for the brevity fields = ("name", "meta_data", "created_by", "city", "supporter") class provinceSerializer (serializers.ModelSerializer): Square Meta Model = Province Square CitySerializer (serializers.ModelSerializer): Square Meta Model = City   

is it. Seriously

Everything is well packed in Jason for you, even if you change your model below the line

But how easy is it to use serial data? Using a serial model will be a simple view:

  class diagram (API): "" "Make a list of all the pictures, or create a new image." "DIF (self, request, format = none): pictures = pictures allocated (files) = picture (file = request): serializer = picture (data = request). Data) if serializer.is_valid (): serializer.save () Return Response (serializer.data, status = status.HTTP_201_CREATED) Return Response (serializer.errors, status = status.HTTP_400_BAD_REQUEST)  

Documentation is really amazing for you to start them cool They also have a sweet that lets you visually navigate through your API < / P>


Comments