简体   繁体   中英

How to serialize models in Django?

I have pretty simple and obvious question that i am trying to search for a while now.

I have a model, Picture , that has foreign keys like created_by , Province , and City .

What I want is to get all model fields serialized to json .

Models.py:

class Picture(models.Model):
    name = models.TextField("Title", max_length=10000, null=True, blank=True)
    meta_data = models.TextField("meta_data", null=True, blank=True)
    created_by = models.ForeignKey(User, related_name="created_by")
    city = models.ForeignKey(City, null=True, blank=True)
    pro = models.ForeignKey(Province, verbose_name="Province")


class Province(models.Model):
    name = models.CharField(max_length=50)
    pi_meta_data = models.TextField(null=True, blank=True)
    intro = models.CharField(max_length=1000, null=True, blank=True)
    description = models.TextField(max_length=10000, null=True, blank=True)


class City(models.Model):
    name = models.CharField(max_length=50)
    pi_meta_data = models.TextField(null=True, blank=True)
    intro = models.CharField(max_length=1000, null=True, blank=True)
    description = models.TextField(max_length=10000, null=True, blank=True)

You can use Django Rest Framework , and serialize models with ease.

Your model serializers would be:

class PicturesSerializer(serializers.ModelSerializer):

    class Meta:
        model = Picture
        # Only including fields in this case to explicitly show that 
        # every field in the Pictures model is serialized. In the rest of 
        # the Serializes fields will be left out for brevity.
        fields = ("name", "meta_data", "created_by", "city", "pro")

class ProvinceSerializer(serializers.ModelSerializer):

    class Meta:
        model = Province


class CitySerializer(serializers.ModelSerializer):

    class Meta:
        model = City

Thats it. Seriously.

Everything is nicely packed into json for you, even if you change your models down the line.

But how easy is it to use the serialized data? A simple view using those serialized models would be:

class PicturesList(APIView):
    """
    List all Pictures, or create a new Picture.
    """
    def get(self, request, format=None):
        pictures = Pictures.objects.all()
        serializer = PicturesSerializer(pictures, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = PicturesSerializer(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)

The documentation is literally amazing. They have a cool tutorial to get you started. They even have a sweet browseable api that lets you visually navigate through your api.

There is a "Django Full Serialization" module which is part of wadofstuff which can serialize related objects among other things. This answer https://stackoverflow.com/a/3753769/187729 has more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM