在我的模型中,用户与其公司的个人资料相关。为了序列化它们,我希望如果发出请求的用户是_staff,那么序列化器必须返回所有公司,而不仅仅是他/她通过模型中的关系所拥有的公司。
什么是......的正确方法:
1)检查用户是否是工作人员 2)如果用户是员工,则返还所有公司或返回与用户相关的个人资料公司。
我想处理此问题的最佳方法是检查 BProfileSerializerRelated ,如果用户是工作人员,然后添加如下内容:
company = serializers.SerializerMethodField('get_companies')
def get_companies(self, obj):
companies = Company.objects.all()
serializer = CompanySerializer(instance=companies, many=True)
return serializer.data
我的当前代码没有考虑用户是否为员工,因此只返回与该用户相关的公司:
models.py
class BUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=40, unique=True)
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=40)
class BProfile(models.Model):
user = models.ForeignKey('BUser')
company = models.ForeignKey('BCompany')
groups = models.ManyToManyField(Group)
class BCompany(models.Model):
name = models.CharField(max_length=64)
dealer = models.ForeignKey(BProfile, related_name='companies', blank=True, null=True)
views.py
@api_view(['GET'])
def current_user_detail(request):
serializer = BUserSerializerRelated(request.user)
return Response(serializer.data)
serializers.py
class BUserSerializerRelated(serializers.ModelSerializer):
bprofile_set = BProfileSerializerRelated(many=True)
class Meta:
model = BUser
fields = ('id', 'bprofile_set', 'username', 'email', 'first_name', 'last_name')
class BProfileSerializerRelated(serializers.ModelSerializer):
company = CompanySerializer()
groups = GroupSerializer(many=True)
dealer_companies = CompanySerializer(many=True)
class Meta:
model = BProfile
fields = ('id', 'dealer_companies', 'company', 'groups')
class CompanySerializer(serializers.ModelSerializer):
sites = SiteSerializer(many=True)
services = ServiceSerializer(many=True)
class Meta:
model = Company
fields = ('id', 'dealer','name', 'cif', 'sites', 'services')
答案 0 :(得分:1)
Serializer在他的上下文词典中有request
个对象。所以你可以从那里获得当前用户。
def get_companies(self, obj):
user = self.context['request'].user
if user.is_staff:
serializer = CompanySerializer(Company.objects.all(), many=True)
else:
serializer = CompanySerializer(instance=companies, many=True)
return serializer.data
答案 1 :(得分:0)
要在序列化程序中访问请求对象,您需要在初始化序列化程序时传递上下文字典,即在tail -f -1000 ~/Library/Logs/CoreSimulator/EE257D24-E3E5-4F9E-B123-97A2587825E5/system.log
views.py
然后在serializer = BUserSerializerRelated(request.user, context={'request': self.request})
中,您可以访问请求用户对象,例如
serializers.py