gpt4 book ai didi

python - Django REST ListCreateAPIView 外键

转载 作者:太空宇宙 更新时间:2023-11-03 14:49:21 24 4
gpt4 key购买 nike

我正在尝试使用 Django 的 ListCreateAPIView 创建一个带有外键的新对象。对外键的引用在 url 中。我尝试使用 lookup_url_kwarg 但是当我发送一个 json 时,它仍然需要我输入一个机构

views.py

class MemorandumCreateView(ListCreateAPIView):
# permission_classes = (IsAuthenticated,)
queryset = Memorandum.objects.all()
lookup_fields = 'institution_id'
lookup_url_kwarg = 'institution_id'
serializer_class = MemorandumSerializer


def get_queryset(self):
institution = self.lookup_url_kwarg['institution_id']
return Memorandum.objects.filter(institution=institution)

序列化器.py

class MemorandumSerializer(ModelSerializer):
# lookup_fields = 'institution_id'
class Meta:
model = Memorandum
fields = "__all__"

urls.py

 url(r'^(?P<institution_id>(\d+))/memorandums', MemorandumCreateView.as_view()),

模型.py

class Memorandum(Model):
MEMORANDUM_CATEGORIES = (
('MOA', 'Memorandum of Agreement'),
('MOU', 'Memorandum of Understanding')
)
AGREEMENT_TYPES = (
('B', 'Bilateral'),
('M', 'Multilateral')
)

institution = ForeignKey(Institution)
agreement = CharField(max_length=12, choices=AGREEMENT_TYPES)
memorandum_category = CharField(max_length=3, choices=MEMORANDUM_CATEGORIES)
memorandum_file = CharField(max_length=512)
version_date = DateField()
date_effective = DateField()
date_expiration = DateField(null=True)
college_initiator = CharField(max_length=5, choices=COLLEGES, null=True)

最佳答案

您可以从您的 URL 中获取 institution_id,然后在自定义 perform_create 中使用它:

class MemorandumCreateView(ListCreateAPIView):
...
def perform_create(self, serializer):
institution = Institution.objects.get(id = self.kwargs['institution_id'])
serializer.save(institution = institution)

关于python - Django REST ListCreateAPIView 外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47060623/

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