Ropali Munshi
Ropali Munshi

Reputation: 3006

Django: Filter records based on one to many relationship

I have following models,

class User(models.Model):
    name = models.CharField(max_length=255)
    ...

class InsuranceProfile(models.Model):
       user = models.ForeignKey(User, on_delete=models.CASCADE)
       ...


class ProductExpertiseMaster(models.Model):
    class Meta:
        db_table = 'product_expertise_master'

    name = models.CharField(max_length=255)

    main_category = models.CharField(max_length=255)


class UserProductExpertise(models.Model): 
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    product_expertise = models.ForeignKey(ProductExpertiseMaster, on_delete=models.DO_NOTHING)

So what I am trying to do is I want to filter records based on various fields some of the belong to User model & some of them belong to the InsuranceProfile model.I am filter the records based on User & InsuranceProfile model which is working fine. Now i want to add one more filter which will be based on the UserProductExpertise model.I want to get all the InsuranceProfiles with User details who have some matching condition with product expertise entries in UserProductExpertise model. Any help would appreciated.

Upvotes: 0

Views: 1264

Answers (2)

Deniz
Deniz

Reputation: 321

I think you should make some changes in your models before proceeding further.

UserProductExpertise model is the bridge table between ProductExpertiseMaster and User, which provides a many-to-many relationship. If you won't add additional fields to UserProductExpertise model, you can drop it and define user relation in ProductExpertiseMaster model.

If you prefer using seperate model for this relationship, on_delete=models.DO_NOTHING is prone to errors, you can change it to models.CASCADE

Here is an example with many-to-many relation:

class User(models.Model):
    name = models.CharField(max_length=255)

class InsuranceProfile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.CharField(("Content"), max_length=500)


class ProductExpertiseMaster(models.Model):
    class Meta:
        db_table = 'product_expertise_master'

    name = models.CharField(max_length=255)

    main_category = models.CharField(max_length=255)
    user = models.ManyToManyField(User, verbose_name=("Users"), related_name="expertises")

For filtering your query:

InsuranceProfile.objects.filter(user__expertises__isnull=False)

Upvotes: 0

ruddra
ruddra

Reputation: 51968

You can try like this using __isnull:

InsuranceProfile.objects.filter(user__userproductexpertise__isnull=False)

It will return all the users who has an entry in in UserProductExpertise model. For querying, you need to use all lowercase of the model name, (ie userproductexpertise) and add __isnull at the end of it.

Upvotes: 2

Related Questions