pythondjangoweb

How to check if model has something inside in django?


I have a model of Branch, and a model of Worker. I want to filter only these branches, which have at least one user inside.

models.py

class Branch(models.Model):
    name = models.CharField(max_length=100)

class Worker(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    fullname = models.CharField(max_length=150)
    branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True, related_name='branch')
    position = models.CharField(max_length=200)
    manager = models.BooleanField(default=False)

I tried to add related_name to worker-branch, but now I don't know how to use it, and is it right way to do so? I also tried to filter like that: Worker.objects.filter(branch=?).exists(). But it doesn't make sense.

At the end I want to have a list of branches which have at least one worker.


Solution

  • Try this and let me know if it helps, it should work, not sure though:

    Branch.objects.filter(branch__isnull=False)
    

    Not elegant at all, but you could also use Count and queryset annotation. Also, "branch" is a terrible name for a set of users assigned to a branch, so the related name should be "users" or "assigned_users" or so.

    EDIT:

    Branch.objects.filter(branch__isnull=False).distinct()
    

    to get rid of duplicates