我有這個文本選擇模型
模型.py
class PostType(models.TextChoices):
DECLARE = 'DECLARE'
UPDATE = 'UPDATE'
SUCCESS = 'SUCCESS'
class Post(models.Model):
# ulid does ordered uuid creation
uuid = models.UUIDField(primary_key=True, default=generate_ulid_as_uuid, editable=False)
created = models.DateTimeField('Created at', auto_now_add=True)
updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True)
creator = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="post_creator")
join_goal = models.ForeignKey(JoinGoal, on_delete=models.CASCADE)
body = models.CharField(max_length=511, validators=[MinLengthValidator(5)])
hash_tags = models.ManyToManyField(HashTag)
type = models.CharField(
choices=PostType.choices,
max_length=50,
)
出于某種原因,在移動前端它回傳為:
反應本機代碼
console.log(response[0].type)
console.log(typeof(response[0].type))
安慰
LOG ('UPDATE', 'Update')
LOG string
以上是由console.log回應和回應console.log typeof中的鍵產生的。這告訴我 Django 將它作為元組發送('<type all caps>', '<type camel case>'),然后 React Native 將其轉換為字串,列印也是如此。為什么會這樣?我可以在 Django 上做些什么來確保只是'Declare','UPDATE'或者'SUCCESS'回傳到本機反應?
查看.py
@api_view(['GET'])
def get_initial_posts(request, count):
serializer = full_post_data_serializer(Post.objects.order_by('-uuid')[:count])
return Response(serializer.data, status=status.HTTP_200_OK)
助手檔案
def full_post_data_serializer(post_query_set: QuerySet):
query_set_annotated = post_query_set.annotate(
creator_username=F('creator__username'),
goal_description=F('join_goal__goal__description'),
goal_uuid=F('join_goal__goal__uuid'),
reply_count=Count('replypost', distinct=True),
cheer_count=Count('cheerpost', distinct=True)
)
return FullPostDataSerializer(query_set_annotated, many=True)
序列化程式.py
class FullPostDataSerializer(serializers.ModelSerializer):
goal_uuid = serializers.SlugField()
creator_username = serializers.SlugField()
reply_count = serializers.IntegerField()
cheer_count = serializers.IntegerField()
goal_description = serializers.SlugField()
class Meta:
model = Post
fields = (
'body', 'join_goal', 'created', 'creator_username', 'goal_description', 'reply_count', 'cheer_count',
'images', 'uuid', 'type', 'creator', 'videos', 'goal_uuid'
)
uj5u.com熱心網友回復:
你可以在這里找到答案:https : //stackoverflow.com/a/28954424/1935069
這在一定程度上取決于您使用的 DRF 和 Django 版本。我要做的是明確并修改序列化程式以使用serializers.SerializerMethodField并獲取選擇欄位的顯示值,如下所示:
class FullPostDataSerializer(serializers.ModelSerializer):
... # your existing code goes here
type = serializers.SerializerMethodField()
def get_type(instance):
return instance.type.value
...
這應該在序列化程式中回傳正確的值。
另一件需要注意的是,這type是python中的保留關鍵字。你可以這樣使用它,但真的不應該,所以我建議如果可能的話重命名變數
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/346378.html
