如何限制request.user的圖像與節點鏈接。我希望我可以這樣做:在django rest框架中限制對外鍵的選擇
photo = models.ForeignKey(
Image,
limit_choices_to={'owner': username},
)
但request.user,而不是用戶名,我不希望使用本地線程。
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')
非常感謝您的回答對你驚人的工作。 – neelix
這仍然是最好的方式嗎?似乎有點雜亂。寧願讓我的序列化器在全局範圍內進行測試 – Eldamir
'serializers.Field'的構造函數似乎沒有'choices'參數了 –