在Angular模板中使用外键属性

时间:2018-02-22 17:12:52

标签: django angular django-rest-framework

我使用Django作为后端(Django Rest Framework)和Angular作为前端。在后端,我有两个型号:

class Post(models.Model):
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
    content = models.TextField(max_length=1000)

class Category(models.Model):
    title = models.CharField(max_length=120)

我相应地序列化了:

class CategorySerializer(ModelSerializer):

    class Meta:
        model   = Category
        fields = '__all__'

class PostSerializer(ModelSerializer):

    class Meta:
        model   = Post
        fields = '__all__'

然后在组件模板中,我想打印特定帖子的类别标题:

<li *ngFor='let post of posts'>
  <div *ngIf='post'>
    <p>{{ post.category.title }}</p>
    <p>{{ post.content }}</p>
  </div>
</li>

我的课程是:

export class Post {
  id: number;
  category: Category;
  content: string;
}

export class Category {
  id: number;
  title: string;
}

为什么{{ post.category.title }}不起作用,而{{ post.content }}有效?这是我的序列化问题还是Angular类的问题?

编辑:API视图:

class PostListCreateAPIView(ListCreateAPIView):
    queryset            = Post.objects.all()
    serializer_class    = PostSerializer

1 个答案:

答案 0 :(得分:2)

创建新的序列化程序RetrivePostSerializer

使用CategorySerializer序列化RetrivePostSerializer

中的相关字段类别
class RetrivePostSerializer(ModelSerializer):
    category = CategorySerializer(read_only=True)

    class Meta:
        model   = Post
        fields = ('id', 'category', 'content')

为GET和POST使用不同的序列化程序,覆盖get_serializer_class方法

class PostListCreateAPIView(ListCreateAPIView):
    queryset = Post.objects.all()

    def get_serializer_class(self):
       if self.request.method == 'POST':
          return PostSerializer
       return RetrivePostSerializer

您的PostSerializer将会更早

class PostSerializer(ModelSerializer):

    class Meta:
        model   = Post
        fields = '__all__'