1

I am having issues with using Django ORM queries in order to retrieve specific information. I have three models all linked by foreign keys, these are Hosts, Groups and Organisations. So each host belong to a group and these groups belong to an organisation. I need to get the query set of all hosts that belong to a specific organisation named 'Y' for example. Below are my model.py, can anybody help me to formulate a query set that will achieve this? or point me in the correct direction to figure this out?

Hosts

class Host(models.Model):
host_name = models.CharField(max_length=120, blank=False, unique=True)
url = models.CharField(max_length=120, blank=False, unique=True)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
slug = models.SlugField(blank=True, null=True)

def __str__(self):
    return self.host_name

Groups

class Group(models.Model):
org_name = models.ForeignKey(Organization, on_delete=models.CASCADE)
group_name = models.CharField(max_length=120, blank=False, unique=True)


def __str__(self):
    return self.group_name

Organizations

class Organization(models.Model):
org_name = models.CharField(max_length=120, blank=False, unique=True)
org_code = models.CharField(max_length=120, blank=False, unique=True, default=GenerateOrganozationCode)

def __str__(self):
    return self.org_name

1 Answer 1

1
host_queryset = Host.objects.filter(group__org_name__org_name='Y')

For more detailed information and examples, please do refer to the official django doc

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works perfectly! Much simpler than I was expecting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.