在django中嵌套多个模型序列化程序

时间:2017-07-17 18:45:46

标签: django django-rest-framework django-serializer

一周大的Django宝宝需要一些帮助!我有以下模型结构。

class Notification(models.Model):
    name = models.CharField(max_length=50, unique=True)
    user = models.ForeignKey(User, related_name="+")

class Route(models.Model):        
    notification = models.ForeignKey(Notification)
    notifier = models.ForeignKey(Notifier)
    destination = models.CharField(max_length=200)

class Notifier(models.Model):
    name = models.CharField(max_length=25, unique=True)

class Match(models.Model):        
    name = models.CharField(max_length=100)
    entity_name = models.CharField(max_length=100, null=True)
    metric_name = models.CharField(max_length=100, blank=True, null=True)
    status = models.IntegerField(blank=True, null=True)
    notification = models.ForeignKey(
        Notification, blank=True, null=True
    )

我想以下列格式获取列表,并希望我的API能够过滤entity_name,metric_name,status_user

{
"routes": {
    "email":["abc@gmail.com"],
    "slack":["name_of_slack_channel"],
},
"name": "sample",
"metric":"CPU",
"entity":"some_enttity",
"status":0,
"user":"ent@gmail.com"
}

通知是路径模型字段notifier: destination的映射。 路线中的每一行都是<notificationID, email, "abc@gmail.com><notificationID, slack, "slackchannel>

的排序

我可以使用routes = serializers.SerializerMethodField()字段并使用select_related('notifier')

获取所需内容
class NotificationSerializer(serializers.ModelSerializer):

    routes = serializers.SerializerMethodField()
    class Meta:
        model = Notification
        fields = (
            'name', 'routes'
        )

    def get_routes(self, obj):
        related_routes = 
             Route.objects.filter(notification_id=obj.pk).
                  select_related('notifier')
        all_routes = {}
        for route in related_routes:
            if route.notifier.name in all_routes:
                all_routes[route.notifier.name] += [route.destination]
            else:
                all_routes[route.notifier.name] = [route.destination]
        return all_routes

但我确信有更好的方法可以做到这一点,而无需进行所有这些处理并且必须在get_routes中获取Route对象。任何帮助,将不胜感激。谢谢!

0 个答案:

没有答案