我想根据 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()),
1 回答
慕森王
TA贡献1777条经验 获得超3个赞
我又自己解决了这个问题。
当我将以下功能添加到视图模型时,我们只能更新属于已登录用户的模型。
def get_queryset(self):
return self.queryset.model.objects.filter(owner=self.request.user)
我们选择使用以下功能自动登录的用户。##
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
查看.py##
class UpdateAdvertiseData(RetrieveUpdateAPIView):
serializer_class = AdvertiseMainSerializer
queryset = Advertise.objects.all()
def get_queryset(self):
return self.queryset.model.objects.filter(owner=self.request.user)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
添加回答
举报
0/150
提交
取消