Serialize a foreingkey and many to many fields in

2019-09-06 17:09发布

问题:

I have the models like this:

class Category(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, max_length=255, blank=True,default=None)
    desc = models.TextField(blank=True, null=True )

    ...

class Post(models.Model):
   title = models.CharField(max_length=255)
   pub_date = models.DateTimeField(editable=False,blank=True)
   author = models.ForeignKey(User, null=True, blank=True)
   categories = models.ManyToManyField(Category, blank=True, through='CatToPost')

   ...


class CatToPost(models.Model):
    post = models.ForeignKey(Post)
    category = models.ForeignKey(Category)

    ...

Here is the serializer:

 class CategorySerializer(serializers.ModelSerializer):
   class Meta:
        model = Category
        fields = ('name','slug')

class PostSerializer(serializers.ModelSerializer):
    categories = CategorySerializer(many=True, required=True)


    class Meta:
        model = Post
        .......

The views.py

class SingleListing(generics.RetrieveUpdateDestroyAPIView):
    queryset = Post.objects.all()
    serializer_class =Post

Serializer

But this doesn't show the category field in the web-browsable view. I only see the Category label, but the input fields of this fields is not there. What is the problem?

回答1:

DRF will not support many=True and rise this Lists are not currently supported in HTML input. Category is not a field it's a model. It will show all the model related fields.

Try this:

serializers.py

class PostSerializer(serializers.ModelSerializer):
    categories = CategorySerializer(required=True)


    class Meta:
        model = Post
        fields = ('id', 'title', 'pub_date', 'author', 'categories')

views.py

class SingleViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

Showing the fields in the web-browserview



回答2:

well, you should write your serializer like this:

class CategorySerializer(serializers.ModelSerializer):
      class Meta:
            model = Category
            fields = ('name','slug')

class PostSerializer(serializers.ModelSerializer):

      class Meta:
            model = Post  
            fields = ('id','{anything you want}','categories')
            depth = 2