外键字段未在Django REST上发布

时间:2019-11-11 14:21:44

标签: python django rest api

所以,我正在为待办任务管理器做一个API,在这个api中,我有很多相互关联的表(一个项目属于一个客户,一个客户就是一个属于的人到城市等等),我希望通过学习如何修复以下示例,我将能够修复其余的表,这些表都有类似的问题。

我的问题是:一个人属于一个城市(已经存在),因此“人”的一个字段是“城市”的外键,我认为它应该是一个整数,即城市ID(人住在1个城市,城市可以容纳N个人)。

但是我无法正常工作。

在django / admin站点上,这一切都可以正常运行。 我可以使用此人的信息创建此人,并在其中有一个选择框,其中包含每个城市的列表,效果很好。

但是当我尝试使用Postman甚至/ api站点进行POST时,曾经没有城市ID的字段,现在在谷歌搜索并尝试了一切之后,我以某种方式添加了城市ID字段,但无法获取它工作。

当前问题是“无法分配'8'(城市ID):...必须是“城市”实例。

我将默认值设置为1,但这不能解决问题,因为在其他表上(项目有一个Client FK,Client有Person FK,等等),问题也相同。

你们对为什么会发生这种情况有任何想法吗?我已经搜索,观看和阅读了类似内容的指南,但无法正确完成。

这是我的文件:

Models.py

class City(models.Model):
    idcity = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, blank=True, null=True)
    uf = models.CharField(max_length=2, blank=True, null=True)

    def __str__(self):
        return (self.name + " - " + self.uf)

    class Meta:
        managed = False
        db_table = 'city'
        verbose_name = 'City'
        verbose_name_plural = 'Cities'

class Person(models.Model):
    idperson = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200, blank=True, null=True)
    phone = models.CharField(max_length=15, blank=True, null=True)
    address = models.CharField(max_length=500, blank=True, null=True)
    email = models.CharField(max_length=200, blank=True, null=True)
    idcity = models.ForeignKey('City', on_delete=models.DO_NOTHING, db_column='idcity', blank=True, null=True, default=1)

    def __str__(self):
        return '{}'.format(self.name)

    class Meta:
        managed = False
        db_table = 'person'
        verbose_name = 'Person'
        verbose_name_plural = 'People'

Serializers.py


class CityDetailSerializer(ModelSerializer):
    idcity = serializers.IntegerField(required=False)
    class Meta:
        model = City
        fields = [
            'idcity ',
            'name',
            'uf',
        ]
        depth = 4


class PersonDetailSerializer(ModelSerializer):
    # name = serializers.CharField()
    # phone = serializers.CharField()
    # address = serializers.CharField()
    # email = serializers.CharField()
    # idcity = serializers.IntegerField()
    idcity = CityDetailSerializer()

    class Meta:
        model = Person
        fields = '__all__'
        depth=2

Views.py

我不知道为什么我的伴侣使用了这么多视图,但是还可以

class CityListAPIView(ListAPIView):
    queryset = City.objects.all()
    serializer_class = CityListSerializer

class CityDetailAPIView(RetrieveAPIView):
    queryset = City.objects.all()
    serializer_class = CityDetailSerializer

# i tried commenting and uncommenting the following
# but it still doesnt work

    def get(self, request, pk=None):
        if pk:
            city = get_object_or_404(City.objects.all(), pk=int(pk))
            serializer = CityDetailSerializer(city)
            return Response(serializer.data)
        cities = City.objects.all()
        serializer = CityDetailSerializer(cities, many=True)
        return Response(serializer.data)

class CityCreateAPIView(CreateAPIView):
    queryset = City.objects.all()
    serializer_class = CityDetailSerializer

class CityUpdateAPIView(UpdateAPIView):
    queryset = City.objects.all()
    serializer_class = CityDetailSerializer

class CityDeleteAPIView(DestroyAPIView):
    queryset = City.objects.all()
    serializer_class = CityDetailSerializer



class PeopleListAPIView(ListAPIView):
    queryset = Person.objects.all()
    serializer_class = PersonListSerializer

class PersonDetailAPIView(RetrieveAPIView):
    queryset = Person.objects.all()
    serializer_class = PersonDetailSerializer

    def get(self, request, pk=None):
        if pk:
            person = get_object_or_404(Person.objects.all(), pk=pk)
            serializer = PersonDetailSerializer(person)
            return Response(serializer.data)
        people = Person.objects.all()
        serializer = PersonDetailSerializer(people, many=True)
        return Response(serializer.data)

class PersonCreateAPIView(CreateAPIView):
    queryset = Person.objects.all()
    serializer_class = PersonDetailSerializer

class PersonUpdateAPIView(UpdateAPIView):
    queryset = Person.objects.all()
    serializer_class = PersonDetailSerializer

class PersonDeleteAPIView(DestroyAPIView):
    queryset = Person.objects.all()
    serializer_class = PersonDetailSerializer

URLs.py

    path('cities/', CityListAPIView.as_view()),
    path('cities/create', CityCreateAPIView.as_view()),
    url(r'^cities/(?P<pk>[0-9]+)/$', CityDetailAPIView.as_view()),
    url(r'^cities/(?P<pk>[0-9]+)/edit/$', CityUpdateAPIView.as_view()),
    url(r'^cities/(?P<pk>[0-9]+)/delete/$', CityDeleteAPIView.as_view()),

    path('people/', PeopleListAPIView.as_view()),
    path('people/create', PersonCreateAPIView.as_view()),
    url(r'^people/(?P<pk>[0-9]+)/$', PersonDetailAPIView.as_view()),
    url(r'^people/(?P<pk>[0-9]+)/edit/$', PersonUpdateAPIView.as_view()),
    url(r'^people/(?P<pk>[0-9]+)/delete/$', PersonDeleteAPIView.as_view()),

如果您需要更多代码或信息,请询问,我真的需要帮助,因为我是一个全新的Django,并且需要通过此大学课程。

还是谢谢你!

1 个答案:

答案 0 :(得分:0)

我如何解决它:

我添加了以下功能,这是我在其他问题中发现的。 感谢对此做出回应的人。

views.py

class PersonCreateAPIView(CreateAPIView):
#    ...    
    def perform_create(self, serializer):
        city = get_object_or_404(City, idcity=self.request.data.get('idcity'))
        return serializer.save(idcity=city)