序列化器中的连接表序列化

时间:2018-04-04 12:12:07

标签: django django-rest-framework django-orm

所以我试图用django序列化程序序列化多个连接表。我找不到办法做到这一点。正在执行的查询是原始sql。 模型如下

class UserDetail(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE)
    mobile_number = models.IntegerField()
    national_id = models.CharField(max_length = 30)
    date_created = models.DateTimeField(auto_now_add = True)
    address = models.CharField(max_length = 250)
    merchant_name = models.CharField(null = True, max_length = 30)

class Account(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE)
    account_number = models.BigIntegerField()
    balance = models.FloatField()
    account_type = models.ForeignKey(AccountType, on_delete = models.CASCADE)

预期结果的json应如下所示

{
  "userdetail": {
                 "mobile_number":""
              },
  "account": {
              "account_number":""
          },
  "user": {
  "first_name": "",
  "last_name": "",
  "email":""
      }
  }

原始sql查询如下

queryset = Account.objects.raw('''SELECT auth_user.first_name,
                                                 auth_user.id,
                                                 auth_user.last_name,
                                                 auth_user.email,
                                                 authentication_userdetail.mobile_number,
                                                 authentication_account.account_number
                                           FROM
                                                 public.auth_user,
                                                 public.authentication_account,
                                                 public.authentication_userdetail
                                           WHERE
                                                 auth_user.id = authentication_userdetail.user_id
                                           AND
                                                 auth_user.id = authentication_account.user_id
                                        ''')

如果有另一种方法可以在不使用原始sql的情况下执行此操作,我将非常感谢它,因为我不是使用django ORM执行原始SQL查询的粉丝

尝试使用此解决方案但我似乎无法理解查询集的序列化方式 Cross-table serialization Django REST Framework

被修改

class UserDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserDetail
        fields = ('mobile_number',)

class AccountSerializer(serializers.ModelSerializer):

    class Meta:
        model = Account
        fields = ('account_number',)


class AccountInfoSerializer(serializers.ModelSerializer):
    user_detail = UserDetailSerializer()
    account = AccountSerializer()
    user = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('user_detail', 'account', 'user')
    def get_user(self, obj):
        return {
            'first_name': 'obj.first_name',
            'last_name': 'obj.last_name',
            'email': 'obj.email',
           }

视图代码

serializer_class = AccountInfoSerializer

def get_queryset(self, *args, ** kwargs):
    user_id = self.request.query_params.get('user_id', None)
    queryset = None
    if user_id is not '':
        queryset = UserDetail.objects.raw()
    return queryset

1 个答案:

答案 0 :(得分:0)

你可以尝试这样的解决方案:

from rest_framework import serializers

class UserDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserDetail
        fields = ('mobile_number',)


class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ('account_number',)


class UserSerializer(serializers.ModelSerializer):
    userdetail = UserDetailSerializer()
    account = AccountSerializer()
    user = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('userdetail', 'account', 'user')

    def get_user(self, obj):
        return {
            'first_name': 'obj.first_name',
            'last_name': 'obj.last_name',
            'email': 'obj.email',
            }