Having two lookup field in viewset in DRF

I have three models as fallow

customuser

userprofle

class UserProfile(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, verbose_name='شناسه کاربر')
    about_me = models.TextField(verbose_name='درباره من', max_length=200, null=True, blank=True)
    timezone = models.ForeignKey(Timezone, on_delete=models.CASCADE, verbose_name='منطقه زمانی', null=True, blank=True)
    location = models.CharField(verbose_name='مکان', max_length=20, null=True, blank=True)
    website = models.CharField(verbose_name='وب سایت', max_length=100, null=True, blank=True)
    profile_header = models.ImageField(verbose_name='تصویر سرآیند پروفایل', null=True, blank=True)
    usercard_background = models.ImageField(verbose_name='تصویر پس زمینه کارت کاربر', null=True, blank=True)
    month_of_birth = models.SmallIntegerField(verbose_name='ماه تولد', null=True, blank=True)
    day_of_birth = models.SmallIntegerField(verbose_name='روز تولد', null=True, blank=True)    

and useremails

class UserEmails(models.Model):    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) 
    profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name='شناسه پروفایل کاربر',default=0)  
    email = models.EmailField(verbose_name='ایمیل')
    is_primary = models.BooleanField(null=True, blank=True, verbose_name='ایمیل اصلی')
    email_verified = models.BooleanField(null=True, blank=True, verbose_name='تاییدیه ایمیل')

customeuser and userprofile have a one-to-one relationship what i want to do is to get user emails based on his/her user_id and profile id i search for solution and find out that i could use two lookup fields in DjangoRestFramework and i implement it as bellow

serializers.py

class CustomUserSerializer(serializers.HyperlinkedModelSerializer):      
    class Meta:
        model = CustomUser                
        fields = ['id', 'email','username', 'date_joined', 'trust_level', 'profile_picture']  

class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
    user = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all())
    
    class Meta:
        model = UserProfile        
        fields = ['user', 'id', 'about_me'] 

class UserEmailSerializer(serializers.HyperlinkedModelSerializer):
    
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        self.kwargs.get('profile_lookup'))
        serializer = self.get_serializer(instance, context={'user_lookup': self.kwargs.get('user_lookup'), 'profile_lookup': self.kwargs.get('profile_lookup')})
        return Response(serializer.data)
    
    class Meta:
        model = UserEmails
        fields = ['profile' ,'email', 'user_lookup', 'profile_lookup' ]  

and views.py

class CustomUserViewSet(viewsets.ModelViewSet):
    queryset = CustomUser.objects.all()
    serializer_class = CustomUserSerializer  
    lookup_field = 'id'

class UserProfileViewSet(viewsets.ModelViewSet):
    queryset = UserProfile.objects.all()   
    serializer_class = UserProfileSerializer
    user_lookup = 'customuser_id'
    profile_lookup = 'userprofile_id'
    lookup_value_converter = 'uuid'
    
    def get_object(self):
        # Get the lookup parameters from the URL
        user_lookup = self.kwargs.get('user_lookup')
        profile_lookup = self.kwargs.get('profile_lookup')       
        # Perform the lookup using both fields
        try:
            obj = UserProfile.objects.get(user=user_lookup, id=profile_lookup)
            return obj
        except UserProfile.DoesNotExist:
            raise Http404('رکورد مربوطه یافت نشد') 

class UserEmailViewSet(viewsets.ModelViewSet):
    queryset = UserEmails.objects.all()
    serializer_class = UserEmailSerializer
    lookup_field = 'profile__id'

also urls.py

users_router = routers.DefaultRouter()
users_router.register(r'users', views.CustomUserViewSet, basename='customuser')
profile_router = routers.DefaultRouter()
profile_router.register(r'profile', views.UserProfileViewSet, basename='profile')
user_email_router = routers.DefaultRouter()
user_email_router.register(r'<uuid:user_id>/profile', views.UserEmailViewSet)

urlpatterns = [
    path('', views.CustomUserViewSet.as_view({'get': 'list', 'post': 'create'}), name='user-list'),
    path('profile/', views.UserProfileViewSet.as_view({'get': 'retrieve'}), name='user-profile'),    
    path('timezone/', views.TimezoneViewSet.as_view({'get': 'list', 'post': 'create'}), name='timezone'),
    path('user_emails/', views.UserEmailViewSet.as_view({'get': 'retrive', 'post': 'create'}), name='user_emails'),
]
# Include the router URLs
urlpatterns = profile_router.urls + user_email_router.urls

the problem is user_lookup and profile_lookup are always None so no records was retrived any help would be appriciated thanks

Вернуться на верх