序列化为AbstractUser的外键对象

时间:2019-02-15 13:17:38

标签: django

我正在成功使用Django REST框架序列化模型,但是想从相关模型中添加字段。我见过其他文章描述了如何使用嵌套序列化程序来实现此目的,但是我的方法有所不同,因为我尝试访问的其他模型是AbstractUser类。 我想从CustomUser序列化UserDefinedEquipName字段。

模型(为清楚起见,删除了一些字段):

accounts / models.py

from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser): 
    UserDefinedEquipName = models.CharField(max_length=50, default = "Default equip",)
    ....

builds / models.py

from accounts.models import CustomUser
from django.contrib.auth import get_user_model

class Build(models.Model):
    author =  models.ForeignKey(get_user_model(),on_delete=models.CASCADE,)
    machineName = models.OneToOneField(max_length=50,blank=True,)
    ....

所以我的想法是将值传递给序列化器,但似乎无法弄清楚如何在不出错的情况下访问值AttributeError: type object 'Build' has no attribute 'CustomUser'

我尝试过: 我的serializers.py:

from rest_framework import serializers
from .models import Data, Build, CustomUser
from django.contrib.auth.models import AbstractUser

class buildStatsAPI_serializer(serializers.ModelSerializer):
    equipName = Build.CustomUser.UserDefinedEquipName
    #also tried:
    #equipName = Build.CustomUser__set.all()

    class Meta:
        fields = ('id','author','machineName','equipName',)
    model = Build

我在这里想念些小东西吗?还是有更好的方法来做到这一点。似乎如果这不是AbstractUser类,那就容易多了。

编辑-添加了views.py

class buildStatsAPI(generics.ListCreateAPIView):#for build stats JSON
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = buildStatsAPI_serializer
    def get_queryset(self):
        machinesOwned =CustomUser.objects.filter(customerTag=self.request.user.customerTag).filter(isDevice=True)
        machineList = []
        for machine in machinesOwned:
            machineList = machineList + [machine.id]
        query = Build.objects.filter(deleted=0, author_id__in=machineList,).values().order_by('pk')
        return query

1 个答案:

答案 0 :(得分:2)

我认为您定义的序列化器不正确。您不能在序列化器中直接引用Model。您需要使用任何一种fields。例如,如果您使用SerializerMethodField,则可以这样尝试:

class buildStatsAPI_serializer(serializers.ModelSerializer):
    equipName = serializers.SerializerMethodField()
    class Meta:
        fields = ('id','author','machineName','equipName',)
        model = Build

    def get_equipName(self, obj):
        # here obj is a build model object
        return obj.author.UserDefinedEquipName

更新

请更新您的get_queryset方法,使其返回这样的查询集(我已经对其进行了重构):

def get_queryset(self):
    query = Build.objects.filter(deleted=0, author__customerTag=self.request.user.customerTag, author__isDevice=True)  # removed .values() because it will return a dictionary
    return query