如何检查Django模型是否包含某些内容?

huangapple go评论88阅读模式
英文:

How to check if model has something inside in django?

问题

我有一个Branch模型和一个Worker模型。我想要筛选出至少有一个用户的那些分支。

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)

我尝试在worker-branch之间添加了related_name,但现在我不知道如何使用它,这样做是否正确?
我还尝试了这样的筛选:Worker.objects.filter(branch=?).exists()。但这没有意义。

最终,我希望获得至少有一个工作人员的分支列表。

英文:

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.

答案1

得分: 0

尝试这个,如果有帮助,请告诉我,应该可以工作,但不确定:

Branch.objects.filter(branch__isnull=False)

一点都不优雅,但你也可以使用Count和查询注释。此外,“branch”对于一组分配给分支的用户来说是一个糟糕的名称,相关名称应该是“users”或“assigned_users”之类的。

编辑:

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

以去除重复项。

英文:

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

答案2

得分: 0

我更喜欢以下的方法(更容易阅读):

Branch.objects.exclude(branch__isnull=True)
英文:

I prefer the following approach (easier to read):

Branch.objects.exclude(branch__isnull=True)

huangapple
  • 本文由 发表于 2023年7月10日 22:43:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76654870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定