gpt4 book ai didi

django - 在Django Rest框架中将选择限制为外键

转载 作者:行者123 更新时间:2023-12-04 05:03:41 26 4
gpt4 key购买 nike

如何限制request.user的图像与节点链接。我希望我可以做类似的事情:

photo = models.ForeignKey(
Image,
limit_choices_to={'owner': username},
)

但是request.user而不是username,并且我不想使用本地线程。

models.py
class Node(models.Model):
owner = models.ForeignKey(User)
content = models.TextField()
photo = models.ForeignKey(Image)

class Image(models.Model):
owner = models.ForeignKey(User)
file = models.ImageField(upload_to=get_upload_file_name)

serializers.py
class ImageSerializer(serializers.ModelSerializer):
owner = serializers.Field('owner.username')

class Meta:
model = Image
fields = ('file', 'owner')

class NodeSerializer(serializers.HyperlinkedModelSerializer):

class Meta:
model = Node
fields = ('content', 'photo', 'owner')

最佳答案

我将通过覆盖get_serializer_class来处理此问题,以在运行时动态返回序列化程序类,并在该字段上设置choices选项:

def get_serializer_class(self, ...):
user = self.request.user
owner_choices = ... # However you want to restrict the choices

class ImageSerializer(serializers.ModelSerializer):
owner = serializers.Field('owner.username', choices=owner_choices)

class Meta:
model = Image
fields = ('file', 'owner')

return ImageSerializer

关于django - 在Django Rest框架中将选择限制为外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22173425/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com