Search code examples
djangodatabasepython-3.xmany-to-many

Django complex Query through database API


I am using django 1.7, python 3.4 I have a model class called 'EnterpriseProfile' which is in one to one relationship with a class named 'Enterprise'. Also there is another model 'User' which has a many to many relationship with 'Enterprise'. Now, in 'EnterpriseProfile' model I want to create a function that returns all the user related to that enterprise. What would be the best way to achieve this through django database API or otherwise using raw SQL query.


Solution

  • Some code would help, but I believe that doing this inside EnterpriseProfile

    note: this depends on how you named some fields.

    you don't need a function:

    profile = EnterpriseProfile.objects.get(pk=1)  # or whatever to get the object
    # next returns all users related to that enterprise in the M2M
    profile.enterprise.users.all()