简体   繁体   English

如何使用 DRf 中的嵌套序列化程序和视图集同时更新和创建?

[英]How to update and create at the same time using nested serializers and viewsets in DRf?

my models:我的模型:

class User(AbstractUser):
    password = models.CharField(max_length=128, blank=True, null=True)
    email = models.EmailField(max_length=254, unique=True)
    dial_code_id = models.CharField(max_length=100)
    mobile_number = models.CharField(max_length=100, unique=True)
    username = models.CharField(max_length=150, unique=True, blank=True, null=True)
    is_active = models.BooleanField(default=True)

    class Meta:
        db_table = "my_user"


class UserLocation(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='location')
    latitude = models.DecimalField(max_digits=8, decimal_places=3)
    longitude = models.DecimalField(max_digits=8, decimal_places=3)
    address = models.TextField()

    class Meta:
        db_table = "user_location"

I have to update 'first_name', 'last_name' and at the same time I have to create an object in the 'UserLocation' table for the same user.我必须更新'first_name'、'last_name',同时我必须在'UserLocation'表中为同一用户创建一个object。 For that I have created a viewset为此,我创建了一个视图集

class BasicInformationViewSet(viewsets.ModelViewSet):
  queryset = User.objects.all()
  serializer_class = BasicInformationSerializer

  def list(self, request, *args, **kwargs):
      custom_data = {
          "status": False,
          "message": 'Method Not Allowed',
      }
      return Response(custom_data, status=status.HTTP_200_OK)

  def create(self, request, *args, **kwargs):
      custom_data = {
          "status": False,
          "message": 'Method Not Allowed',
      }
      return Response(custom_data, status=status.HTTP_200_OK)

  def update(self, request, *args, **kwargs):
      instance = self.get_object()
      serializer = self.get_serializer(instance, data=request.data)
      if serializer.is_valid():
          serializer.save()
          custom_data = {
              "status": True,
              "message": 'Successfully added your basic information',
          }
          return Response(custom_data, status=status.HTTP_200_OK)
      else:
          custom_data = {
              "status": False,
              "message": serializer.errors,
          }
          return Response(custom_data, status=status.HTTP_200_OK)

Serializer for the above views:上述视图的序列化器:

class UserLocationSerializer(serializers.ModelSerializer):
  latitude = serializers.DecimalField(max_digits=8, decimal_places=3, required=True)
  longitude = serializers.DecimalField(max_digits=8, decimal_places=3, required=True)
  address = serializers.CharField(required=True)

  class Meta:
      model = UserLocation
      fields = "__all__"


class BasicInformationSerializer(serializers.ModelSerializer):
  first_name = serializers.CharField(required=True)
  last_name = serializers.CharField(required=True)
  location = UserLocationSerializer()

  class Meta:
      model = User
      fields = ['first_name', 'last_name', 'location']

  def update(self, instance, validated_data):
      instance.first_name = validated_data.get('first_name', instance.first_name)
      instance.last_name = validated_data.get('last_name', instance.last_name)
      instance.save()
      return instance

The 'first_name' and 'last_name' is getting updated but the fields in 'UserLocation' model is not being updated/created. 'first_name' 和 'last_name' 正在更新,但 'UserLocation' model 中的字段未更新/创建。

Thank you.谢谢你。

modelViewSet jas an attribute http_method_name that say what http method allow to access this class so your code be like: modelViewSet jas 属性 http_method_name 说明了 http 方法允许访问此 class 的内容,因此您的代码如下:



class BasicInformationViewSet(viewsets.ModelViewSet):
  queryset = User.objects.all()
  serializer_class = BasicInformationSerializer
  http_method_names = ['put']


  def update(self, request, *args, **kwargs):
      instance = self.get_object()
      serializer = self.get_serializer(instance, data=request.data)
      if serializer.is_valid():
          serializer.save()
          custom_data = {
              "status": True,
              "message": 'Successfully added your basic information',
          }
          return Response(custom_data, status=status.HTTP_200_OK)
      else:
          custom_data = {
              "status": False,
              "message": serializer.errors,
          }
          return Response(custom_data, status=status.HTTP_200_OK)

in this code you write i didn't see any block of code that create a UserLocation.在您编写的这段代码中,我没有看到任何创建 UserLocation 的代码块。 however if you have a query that get UserLocation an belong it get User;但是,如果您有一个获取 UserLocation 属于它的查询,则获取 User; update user but when access user by UserLocation query you see the old user first name or etc you must use ex: ( user_location.refresh_from_db() ) to update your query of UserLocation.更新用户,但是当通过 UserLocation 查询访问用户时,您会看到旧用户名等,您必须使用 ex: ( user_location.refresh_from_db() ) 来更新您对 UserLocation 的查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM