piyushnbali
piyushnbali

Reputation: 35

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

I am making follow-following logic in DRF Below are my codes.

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')

Below are my serializers.

    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']
    

Now my 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)

In response, I get userId and FollowsId but I want the full user Model. I tried depth = 1 and models.PrimaryRelatedFields() it works but only one time after I delete follow association object and next time I try to insert it says the username already exists. Please Help.

Upvotes: 0

Views: 75

Answers (1)

Yasii
Yasii

Reputation: 1842

Try using Nested Serializers

You can create a new serializer class for the nested serializer and include only the fields you want. You can use the same serializer for both fields

Upvotes: 1

Related Questions