1

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)
Community
  • 1
  • 1
A.J.
  • 8,557
  • 11
  • 61
  • 89
  • Have you tried to pass column names to `queryset.values()`? I know that idea of "magically generating" is quite attractive, but not very usable in a real world. I'm using specific DTO factories that produces simple dictionaries or list of dictionaries; eg. `def pictures_list_dto_factory(picture_queryset)` or/and `def picture_details_dto_factory(picture_instance)`. You can easily serialize output from these factories, for example using `json.dumps`. If this is not a solution for you, please provide more details about your use case. – marcinn Feb 19 '14 at 12:31

2 Answers2

3

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.

agconti
  • 17,780
  • 15
  • 80
  • 114
  • I really like the answer and the code simplicity. but my question remains. I want to get foreign key data. like picture = pic.name, pic.created_by.name, pic.created_by.id, pic.created_by.email. – A.J. Feb 19 '14 at 13:31
  • @user570826 The foreign key fields in Picture are all serialized in the PictureSerializer as well! Do you want the reverse relationship in the other models? – agconti Feb 19 '14 at 14:05
  • @user570826 ie. The fields serialized in the PictureSerializer are name, meta_data, created_by, city, and pro. – agconti Feb 19 '14 at 14:12
0

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.

Community
  • 1
  • 1
waarg
  • 1