Search code examples
pythondjangodjango-ninja

Multiple QuerySet to another Model


I'm writing the following code to search about category in profile model using Django ninja framework, if i retrieve only the fields in profile all query return, but when i need to get the username from the user model only one record return from the loop.

profile.py

class Profile(models.Model):
    SERVICEPROVIDER = 'service_provider'
    CUSTOMER = 'customer'
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    conf_password = models.CharField(max_length= 124)
    category =  models.CharField(max_length= 80, blank=True, null=True)
    click = models.IntegerField(blank=True, default=0)
    date_clicked = models.DateTimeField(auto_now_add=True, blank=True,null=True)
    image_path = models.ImageField(upload_to='user_uploads/', blank=True)
    role = models.CharField(max_length=100, choices=[
        (SERVICEPROVIDER, SERVICEPROVIDER),
        (CUSTOMER, CUSTOMER),])
    
    profile_info = models.JSONField(blank=True, null=True)

    def __str__(self):
        return f'{self.user.username}'

auth.py

@auth.get("/search/{category}", auth=None, response={200: searchSchemaout, 404: MessageOut})
def search(request, category:str):
    profile = Profile.objects.filter(category__icontains=category).values()
    for i in range(len(profile)):
        user = get_object_or_404(User,id=profile[i]['id'])
        return 200, {
            "user": user,
            "profile": profile[i]
        }

auth.py Schema

class UserSchemaOut(Schema):
    username: str
    
class profileSchemaout(Schema):
    role: str
    category: str  

class searchSchemaout(Schema): 
    user: UserSchemaOut
    profile: profileSchemaout

The result:

{
  "user": {
    "username": "ahmed"
  },
  "profile": {
    "role": "service_provider",
    "category": "doors"
  }
}

Solution

  • I found the solution, maybe its help someone

    @offices.get("/{category}/{user_id}", auth=None, response={200: List[searchSchemaout], 404: MessageOut})
    def category(request, category:str):
        
        cat_qs = Profile.objects.all().filter(category__icontains=category)
        if cat_qs:
            return cat_qs
        else:
           return 404, {'message': 'This category not found.'} 
        
    

    the schema:

    class UserSchemaOut(Schema):
        pk: int
        username: str
        
    class searchSchemaout(Schema): 
        user: UserSchemaOut
        category: str 
        image_path : str 
        role: str
        address: str