如何使用外键保存数据并在 drf 中检索完整模型?

How to save data using foreign key and retrieve full model in drf?

我在DRF中做follow-following逻辑下面是我的代码。

Models.py

class CustomUser(AbstractUser):
email = models.EmailField(_('email address'), unique=True)
userId =  models.UUIDField(primary_key = True,default = uuid.uuid4,editable = False,unique=True)
gender = models.CharField(max_length=1,default='M')
profilePic = models.URLField(max_length=200,default='https://cdn.pixabay.com/photo/2015/10/05/22/37/blank-profile-picture-973460_960_720.png')
bio = models.TextField(null=True)
viewCount = models.IntegerField(default=0)
followers = models.IntegerField(default=0)
followings = models.IntegerField(default=0)
countryCode = models.CharField(max_length=255,default='+91')
country = models.CharField(max_length=255,default="India")
phoneNumber = models.CharField(max_length=10,default="0000000000")

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

objects = CustomUserManager()

def __str__(self):
    return self.email


class followAssociation(models.Model):
    user = models.ForeignKey(CustomUser,related_name='user',on_delete=CASCADE)
    follows = models.ForeignKey(CustomUser,related_name='follows',on_delete=CASCADE)
    class Meta:
        unique_together = ('user', 'follows')

下面是我的序列化程序。

    Serializers.py
    from django.db.models import fields
from rest_framework import serializers
from users.models import CustomUser,followAssociation

class userSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        fields = ('first_name','last_name','email','username','password','is_active','is_staff','is_superuser','bio','gender',
        'viewCount','profilePic','userId','followers','followings','countryCode','country','phoneNumber')
        read_only_fields = ['is_active', 'is_staff', 'is_superuser']
        extra_kwargs = {'password': {'write_only': True, 'min_length': 4,'required': False},'username': {'required': False},'email': {'required': False}}

class followAssociationSerializers(serializers.ModelSerializer):
    class Meta:
        model = followAssociation
        fields = ['user','follows']
    

现在我的 APIVIEW class

views.py
class followAssociationAPIView(APIView):
parser_classes = [JSONParser]
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]

def get(self, request,format = None):
    data = {"user":request.user.userId}
    follows= get_object_or_404(CustomUser.objects.all(),userId = request.query_params["id"])
    data["follows"]  = follows.userId
    followAssociation = followAssociationSerializers(data = data)
    if followAssociation.is_valid(raise_exception=True):
        followAssociation.save()
        return Response(followAssociation.data,status=status.HTTP_202_ACCEPTED)
    return Response(followAssociation.errors,status= status.HTTP_400_BAD_REQUEST)

def delete(self,request,format = None):
    relation = get_object_or_404(followAssociation.objects.all(),follows = request.query_params["id"])
    try:
     data = followAssociationSerializers(relation)
     relation.delete()
     return Response(data.data,status=status.HTTP_200_OK)
    except:
        return Response(status=status.HTTP_302_FOUND)

作为响应,我得到了 userId 和 FollowsId,但我想要完整的用户模型。 我尝试了 depth = 1 和 models.PrimaryRelatedFields() 它有效,但在我删除跟随关联对象后只有一次,下次我尝试插入它时说用户名已经存在。请帮助。

尝试使用 Nested Serializers

您可以为嵌套的序列化程序创建一个新的序列化程序 class,并且只包含您需要的字段。您可以对两个字段使用相同的序列化程序