如何通过外键Django序列化多对多?

时间:2015-06-08 17:00:57

标签: django django-models many-to-many django-serializer

我有模特" B"通过外键与多对多:

class DManager(m.Manager):

    def get_by_natural_key(self, name):
        return self.get(name=name)


class D(m.Model):
    objects = DManager()
    id = m.AutoField(primary_key=True)
    name = m.CharField(max_length=250, unique=True, null=False)

    def natural_key(self):
        return (self.name)


class A(m.Model):
    id = m.IntegerField(unique=True, null=False, primary_key=True)
    name = m.CharField(max_length=250, null=True)


class B(m.Model):
    id = m.IntegerField(unique=True, null=False, primary_key=True)
    name = m.CharField(max_length=250, null=True)
    type = m.ForeignKey(D)
    bs = m.ManyToManyField(A, through='C')

    def natural_key(self):
        ## ?natural key for many-to-many?
        return(self.name, self.type.natural_key(), ?????)


class C(m.Model):
    a_id = m.ForeignKey(A)
    b_id = m.ForeignKey(B)

我可以通过外键(B-D)获得关系,但我无法在我的ajax.py中获得多对多(B-A)的关系:

....
if request.is_ajax():
    aj_d = json.loads(request.body.decode('utf-8'))
    raw_data = serializers.serialize(
         'python', m.B.objects.filter(
          bs__a_id__in=aj_d['data']).distinct(),
    use_natural_foreign_keys=True)
    output = json.dumps(raw_data)
    return HttpResponse(output, content_type='application/json')

例如,可能存在另一种通过values()的方式。但我对转储列表的问题有疑问 - "不是JSON可序列化":

...
    raw_data = m.B.objects.filter(
              bs__a_id__in=aj_d['data']).distinct().values()
    output = json.dumps(raw_data)

1 个答案:

答案 0 :(得分:0)

解决方案:

def push_data(request):

    q = m.B.objects

    if request.is_ajax():
        data = json.loads(request.body.decode('utf-8'))

    if 'req_1' in data:
        q = q.filter(bs__id__in=data['req_1'])

    if 'req_2' in data:
        q = q.filter(type__id__in=data['req_2'])

    actual_data = q.values('name', 'id', 'type__name')

    mtm_get(actual_data) ## down

    return HttpResponse(json.dumps(list(actual_data)),
                        content_type='application/json; charset=utf8')

多对多:

def mtm_get(data):
    for d in data:
        d['a_name'] = ', '.join(''.join(i) for i in m.B.objects.filter(
            pk=d['id']).values_list('bs__name'))