Django模型实例字段与Dict的ManyToMany关系

时间:2016-05-23 11:57:00

标签: python json django django-models

我正在尝试创建一个简单的操作,从数据库中获取一条记录(具有ManyToMany关系),然后显示JSON序列化实例,以下是我现在的处理方式:

服务模式:

class SystemService(models.Model):
    name = models.CharField(max_length=35, unique=True, null=False, blank=False)
    verion = models.CharField(max_length=35, unique=True, null=False, blank=False)

    def __str__(self):
        return self.name

服务器型号:

class Server(models.Model):
    name = models.CharField(max_length=35, unique=True, null=False, blank=False)
    ip_address = models.GenericIPAddressField(protocol='both', unpack_ipv4=True,
                                              null=False, blank=False, unique=True)
    operating_system = models.ForeignKey(OperatingSystem, null=False, blank=False)
    monitored_services = models.ManyToManyField(SystemService)
    info = models.CharField(max_length=250, null=True, blank=True)
    pause_monitoring = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

以下是现在使用muj-gabriel的答案:

def get_server(request, server_id):
    try:
        server_object = Server.objects.get(id=server_id)
        data = {
            'name': server_object.name,
            'ip_address': server_object.ip_address,
            'os': server_object.operating_system.name,
            'info': server_object.info,
            'monitoring_paused': server_object.pause_monitoring,
            'created_at': server_object.created_at,
            'update_at': server_object.updated_at,
            'services': {service['id']: service['name'] for service
                     in server_object.monitored_services.values('id', 'name')}
        }
        return JsonResponse(data)
    except Server.DoesNotExist:
        return JsonResponse({'error': 'Selected object does not exits!'})

我不认为我所做的就足够了,因为每次我需要将一个实例作为JSON时我必须重复相同的事情,所以我想知道是否有一个pythonic和动态的方法来做它?

2 个答案:

答案 0 :(得分:1)

如果你只需要价值观' id'和' name'我建议用这个:

'services': {service['id']: service['name'] 
             for service in server_object.monitored_services.values('id', 'name')}

请参阅django docs

此外,您可以将代码移动到Model类的属性中,以便在其他地方重用它。

class Server(models.Model):
    .......

    @property
    def data(self):
        return {
            'name': self.name,
            'ip_address': self.ip_address,
            'os': self.operating_system.name,
            'info': self.info,
            'monitoring_paused': self.pause_monitoring,
            'created_at': self.created_at,
            'update_at': self.updated_at,
            'services': {service['id']: service['name'] for service in self.monitored_services.values('id', 'name')}
        }

您的查看功能将是:

def get_server(request, server_id):
    try:
        server_object = Server.objects.get(id=server_id)
        return JsonResponse(server_object.data)
    except Server.DoesNotExist:
        return JsonResponse({'error': 'Selected object does not exits!'})

答案 1 :(得分:0)

在看了一下Django文档后,我找到了model_to_dict函数,它基本上可以做我需要的东西(Model实例到Dict),但是对于ManyToMany关系,它只返回一个PK列表,所以我自己写了一个函数在它上面:

def db_instance2dict(instance):
    from django.db.models.fields.related import ManyToManyField
    metas = instance._meta
    data = {}
    for f in chain(metas.concrete_fields, metas.many_to_many):
        if isinstance(f, ManyToManyField):
            data[str(f.name)] = {tmp_object.pk: db_instance2dict(tmp_object)
                                 for tmp_object in f.value_from_object(instance)}
        else:
            data[str(f.name)] = str(getattr(instance, f.name, False))
    return data

希望它可以帮助别人。