HI all,

I have the follow models . I want to find all the categories from the 
UserCategory table along with the budget for each category from the 
UserBudget model. I tried with select_related and prefetch and filtered 
with user_id but then it only returns budget that has matched with user_id. 
But i want to retrieve all the categories whether user has budget or not.

class UserCategory(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    cat = models.ForeignKey('preference.Category', null=True, 
on_delete=models.CASCADE)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Category(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    is_active = models.BooleanField(default=True)

class UserBudget(models.Model):
    cat = models.ForeignKey('preference.Category', on_delete=models.CASCADE)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    budget = models.DecimalField(default=0.00, decimal_places=2, max_digits=20)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


I tried following approach :

user_cats = 
UserCategory.objects.prefetch_related('cat__userbudget_set__user').filter(user_id=user_id)

Enter code here...
But the above query only returns UserCategory that matched with the 
user_id. But i want the following result. 

select uc.id as cat_id, uc.user_id cat_user, ub.user_id as budget_user, 
ub.cat_id as budget_cat from user_categories as uc
left outer join user_budget as ub on uc.id = ub.cat_id 
where uc.user_id = 2




Please help. Thanks. 

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/99366754-8702-4939-adaa-e271ae3ed144%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to