我有发布模型和标识符模型。两者都是相关的,因为post的PK是标识符的FK。从post表返回数据时,我还需要返回标识符表数据。我怎样才能有效地做到这一点?
models.py
class SharedIdentifier(models.Model):
post = models.ForeignKey('post.Post',related_name='ref_posts', on_delete=models.CASCADE)
label = models.CharField(max_length=32)
value = models.CharField(max_length=50)
serializers.py
class SharedIdentifierSerializer(serializers.ModelSerializer):
class Meta:
model = SharedIdentifier
fields = ('id', 'post', 'label', 'value',)
read_only_fields = ('post')
class PostSerializer(serializers.ModelSerializer):
author = UserSerializer(required=False,)
ref_user = UserSerializer(read_only=True)
ref_user_id = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), write_only=True, source='ref_user')
identifier = serializers.CharField(max_length=32, write_only=True)
identifier_info = SharedIdentifierSerializer(required=False,many=True,read_only=True)
class Meta:
model = Post
fields = ('id', 'author', 'ref_user', 'ref_user_id', 'status', 'message', 'type', 'parent_id', 'rating', 'create_date', 'close_date','identifier','identifier_info',)
read_only_fields = ('status', 'close_date', 'author', 'ref_user','identifier_info',