在下面的代码中,我需要badge_color
,badge_text
应该显示在user_detail
方法下
型号.py
class User(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
user_name = models.CharField(max_length=50, unique=True)
user_badges = models.ManyToManyField(Badges,related_name='badges', null=True,blank=True,)
class Badges(models.Model):
badge_text = models.CharField(max_length=50)
badge_color = models.CharField(max_length=50)
class Comments(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, max_length=50, unique=False)
date = models.DateTimeField("date of comment", default=timezone.now)
comment_text = models.CharField(max_length=2500)
注释类的序列化程序
class CommentsSerializer(serializers.ModelSerializer):
user_detail = serializers.SerializerMethodField()
class Meta:
model = Comments
fields =[date,comment_text,user_detail]
def get_user_detail(self, obj):
if obj.user:
return {
"id": obj.user.id,
"user_name": obj.user.user_name,
"profile_pic": profile_pic,
}
else:
return None
Views.py
..........
.............
qs=Comments.objects.all()
comments=CommentsSerializer(qs, many=True)
您可以执行以下操作:
class BadgeSerializer(serializers.ModelSerializer):
class Meta:
model = Badges
fields =[badge_color, badge_text]
class CommentsSerializer(serializers.ModelSerializer):
user_detail = serializers.SerializerMethodField()
class Meta:
model = Comments
fields =[date,comment_text,user_detail]
def get_user_detail(self, obj):
if obj.user:
badges = BadgeSerializer(source='obj.user.user_badges', many=True)
return {
"id": obj.user.id,
"user_name": obj.user.user_name,
"profile_pic": profile_pic,
"user_badges": badges.data
}
else:
return None