Django REST ListCreateAPIView外键

时间:2017-11-01 17:37:07

标签: python django django-rest-framework

我尝试使用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)

serializers.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()),

models.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)

2 个答案:

答案 0 :(得分:3)

您可以从网址抓取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)

答案 1 :(得分:1)

lookup_field不是lookup_fields。设置完成后,lookup_field_kwarg将默认使用相同的。{/ p>

在你的模特中:

如果您希望能够创建没有关联机构的备忘录,则

institution = ForeignKey(Institution)需要具有null=True参数。我相信ModelSerializer会接受该更改并在它为您创建的PrimaryKeyRelatedField上设置allow_null=True

http://www.django-rest-framework.org/api-guide/fields/#core-arguments