如何在Rest Framwork中将两个表的数据合并为JSON?

时间:2018-06-25 17:59:45

标签: python django django-rest-framework

我其余的框架序列化器如下:

class ResultSerializer(serializers.ModelSerializer):
    addline = serializers.JSONField();
    city = serializers.JSONField();
    unitcode = serializers.JSONField();
    maid = serializers.JSONField();

    class Meta:
        model = address
        fields = ('addline', 'city', 'unitcode', 'maid')

我有两个模型:

class address(models.Model):
    addline = models.CharField(max_length=120)
    city = models.CharField(max_length=120)
    unitcode = models.CharField(max_length=120)
    maid = models.CharField(primary_key=True)

class dep(models.Model):
    maid = models.CharField(primary_key=True)
    unit = models.CharField(max_length=120)

这是过滤器的示例:

queryset = address.objects.filter(addline__icontains=‘110A Ave’)

我得到的数据当前是:

       [ {
            "addline": "14075 110A Ave",
            "city": "Surrey",
            "unitcode": "U",
            "maid": 113091
        },
        {
            "addline": "14143 110A Ave",
            "city": "Surrey",
            "unitcode": "S",
            "maid": 113104,
      ]

但是我想要的是,当单位代码为“ U”时,会有更多的项目:单位,如下所示:

       [ {
            "addline": "14075 110A Ave",
            "city": "Surrey",
            "unitcode": "U",
            "maid": 113091
        },
        {
            "addline": "14143 110A Ave",
            "city": "Surrey",
            "unitcode": "S",
            "maid": 113104,
            "unit": [ "A-101", "A-102", "A-103", "A-104"]
        }
      ]

update2:

基于http://www.django-rest-framework.org/api-guide/relations/#the-queryset-argument,我当前的Models.py如下:

class address(models.Model):
    addline = models.CharField(max_length=120)
    city = models.CharField(max_length=120)
    unitcode = models.CharField(max_length=120)
    maid = models.CharField(primary_key=True)

class dep(models.Model):
    maid = models.ForeignKey(address, related_name='tracks', 
                             on_delete=models.CASCADE)
    unit = models.CharField(max_length=120)

serializers.py如下:

class ResultSerializer(serializers.ModelSerializer):
    tracks = serializers.StringRelatedField(many=True)
    class Meta:
        model = address
        fields = ('addline', 'city', 'unitcode', 'tracks')

但是它不起作用,有什么问题吗?

3 个答案:

答案 0 :(得分:1)

我这样构建序列化程序,注意深度归因于您的Meta类,他控制着您想如何进行连接的深度...如果设置为1(默认值)他将只带对象ids ... 2他将带对象,但是如果对象中有对象,则应使用3 ...

from rest_framework import serializers

class FooSerializer(serializers.ModelSerializer):
    bar = serializers.PrimaryKeyRelatedField(queryset=Bar.objects.all())

    class Meta:
        model = Foo
        fields = ('bar',) 
        depth = 2 # this do the magic!

编辑:您应该在关系中使用ForeignKeys ...但是,如果您不想这样做,则可以覆盖您的类queryset并加入这两个查询集

这里是一个示例:https://teamtreehouse.com/community/django-rest-framework-override-get-queryset

EDIT2 :我想您可以像这样配置模型,我将为女仆分配一种,为地址分配一种,您可以使用您的dep类与之建立联系

class Address(models.Model):
   ...

class Maid(models.Model):
   ...

class Dep(models.Model):
    maid = models.ForeignKey(Maid, unique)
    address = models.ForeignKey(Address)
    ...

您的序列化器将是这样

class DepSerializer(serializers.ModelSerializer):
    maid = serializers.PrimaryKeyRelatedField(queryset=Maid.objects.all())
    address = serializers.PrimaryKeyRelatedField(queryset=Address.objects.all())

    class Meta:
        model = Dep
        fields = ('__all__') 
        depth = 2 # With 2 will bring full data from Maid and Address Table

答案 1 :(得分:0)

class AddressSerializer(ModelSerializer):

  class Meta:
    model = Address
    fields = ['addline', 'city', 'unitcode', 'maid']

现在您要添加详细信息单元,有多个。

如果两个表通过FK相关联,则可以查找主题“相关字段http://www.django-rest-framework.org/api-guide/relations/

您可以创建这样的方法

class AddressSerilaizer(ModelSerilizer):
  units = SerilizerMethodField()

  def get_units(self, obj):
    return # your logic here

顺便说一句,您的格式略有偏离,类名始终为CamelCase。

答案 2 :(得分:0)

这不是标准方法(models.py):

 class Address(models.Model):
     addline = models.CharField(max_length=120)
     city = models.CharField(max_length=120)
     unitcode = models.CharField(max_length=120)
     maid = models.CharField(primary_key=True)

     @property
     def unit_json(self):
         dep = Dep.objects.get(maid=self)
         if dep:
            return dep.unit

     def as_json(self):
       return dict(
           addline=self.addline,
           city=self.city,
           unitcode=self.unitcode,
           maid=self.maid,
           unit=self.unit_json,
       )

然后

 queryset = address.objects.filter(addline__icontains=‘110A Ave’)
 queryset_json = [ob.as_json() for ob in queryset]