我想更新我创建的模型。但是,我想通过模型的 id 来做到这一点

我想根据 id 号更新我的模型。我怎样才能做到这一点?我可以更新模型,但我想通过 id 执行此操作,我遇到的另一个问题是我只希望创建者能够更新模型


Model.py

    class Advertise(models.Model):

        owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True)

        title = models.CharField(max_length=100, verbose_name="ilan başlığı")

        description = models.TextField(max_length=500, verbose_name="ilan açıklaması")

        price = models.PositiveIntegerField(default=0, verbose_name="Fiyat")

        square_meter = models.PositiveIntegerField(default=0, verbose_name="Metrekaresi")

        number_of_rooms = models.PositiveIntegerField(choices=NumberOfRoomsChoices.CHOICES, 

        verbose_name="Oda sayısı")

        building_age = models.PositiveIntegerField(choices=NumberOfBuildingAgeChoices.CHOICES, 

        verbose_name="Bina Yaşı")

        floor = models.PositiveIntegerField(choices=NumberOfFloorChoices.FLOOR_CHOICES, 

        verbose_name="Bulunduğu Kat")

序列化器##

class AdvertiseMainSerializer(ModelSerializer):

    class Meta:

        model = Advertise

        fields = '__all__'

查看.py##

class UpdateAdvertiseData(UpdateAPIView):

    serializer_class = AdvertiseMainSerializer

    queryset = Advertise.objects.all()


    def perform_create(self, serializer):

        serializer.save(owner=self.request.user)

网址.py##

url(r'^UpdateAdvertiseData/(?P<pk>[-\w]+)/$', UpdateAdvertiseData.as_view()),


繁星点点滴滴
浏览 98回答 1
1回答

慕森王

我又自己解决了这个问题。当我将以下功能添加到视图模型时,我们只能更新属于已登录用户的模型。def get_queryset(self):&nbsp; &nbsp; return self.queryset.model.objects.filter(owner=self.request.user)我们选择使用以下功能自动登录的用户。##def perform_create(self, serializer):&nbsp; &nbsp; serializer.save(owner=self.request.user)查看.py##class UpdateAdvertiseData(RetrieveUpdateAPIView):&nbsp; &nbsp; serializer_class = AdvertiseMainSerializer&nbsp; &nbsp; queryset = Advertise.objects.all()&nbsp; &nbsp; def get_queryset(self):&nbsp; &nbsp; &nbsp; &nbsp; return self.queryset.model.objects.filter(owner=self.request.user)&nbsp; &nbsp; def perform_create(self, serializer):&nbsp; &nbsp; &nbsp; &nbsp; serializer.save(owner=self.request.user)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python