【发布时间】:2015-06-23 06:04:06
【问题描述】:
问题 - 我有一个使用 django-rest-framework(django v1.7.7,django-rest-framework v3.1.1)的 REST 服务器。在通知中,我让用户知道他们是否收到了新的好友请求,或者获得了新的徽章。还有其他通知类型,但这个简单的例子可以解释我的问题。
在我的 GET 响应中,我想通过类型确定的动态相关对象获取通知。如果类型是friendreq,那么我希望relatedObject 是一个用户实例,带有一个UserSerializer。如果类型是badge,我想让relatedObject 成为一个带有BadgeSerializer 的Badge 实例。
注意:我已经有了这些其他的序列化器(UserSerializer、BadgeSerializer)。
以下是我想要在回复中实现的目标:
{
"id": 1,
"title": "Some Title",
"type": "friendreq"
"relatedObject": {
// this is the User instance. For badge it would be a Badge instance
"id": 1,
"username": "foo",
"email": "foo@bar.com",
}
}
以下是我所拥有的模型和序列化程序:
# models.py
class Notification(models.Model):
"""
Notifications are sent to users to let them know about something. The
notifications will be about earning a badge, receiving friend request,
or a special message from the site admins.
"""
TYPE_CHOICES = (
('badge', 'badge'),
('friendreq', 'friend request'),
('system', 'system'),
)
title = models.CharField(max_length=30)
type = models.CharField(max_length=10, choices=TYPE_CHOICES)
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="user")
related_id = models.PositiveIntegerField(null=True, blank=True)
# serializers.py
class NotificationSerializer(serializers.ModelSerializer):
if self.type == "badge":
related_object = BadgeSerializer(
read_only=True,
queryset=Badge.objects.get(id=self.related_id)
)
elif self.type == "friendreq":
related_object = FriendRequestSerializer(
read_only=True,
queryset=FriendRequest.objects.get(id=self.related_id)
)
class Meta:
model = Notification
此代码不起作用,但希望它能够解释我想要完成的工作以及我想要前进的方向。也许这个方向是完全错误的,我应该尝试使用其他方法来实现这一点。
我尝试的另一个选择是使用 SerializerMethodField 并在方法中执行此操作,但对于这种尝试基于另一个字段返回序列化对象的情况来说,这似乎并不干净。
【问题讨论】:
标签: django django-rest-framework