Django 表单查询集:排除现有记录

Django form queryset: excluding existing records

在Django中,我有以下几个模型:一个是分店,一个是基础水果,一个是每个分店卖的水果:

from django.db.models import Q

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

class Fruit(models.Model):
    name = models.CharField()
    ...

class BranchFruit(models.Model):
    branch = models.ForeignKey(Branch)
    fruit = models.ForeignKey(Fruit)
    ...

    class Meta:
        unique_together = ('branch', 'fruit')

提供了一个用于添加新水果的表单,查询集应排除该商店中已有的水果。我正在考虑使用以下内容:

表格:

class BranchFruitForm(modelForm):
    fruit = forms.ModelChoiceField(queryset=Fruit.objects.all())

    def __init__(self, *args, **kwargs):
        super(BranchFruitForm, self).__init__(*args, **kwargs)
        excludes = BranchFruit.objects.filter(branch=args)
        includes = Fruit.objects.filter(~Q([exc.fruit for exc in excludes]))
        self.fields['fruit'].queryset = includes

views.py 包含:

if request.method=='GET':
    branch = request.user.branch   # The branch shop the user belongs to
    return render(request, template, {'branchFruitForm':BranchFruitForm(branch)})

但是 BranchFruitForm 在 excludes 语句处失败并显示以下消息:

int() argument must be a string or a number, not 'Branch'

我该如何解决?

我认为它需要 ID 而不是对象。尝试构建一个 ID 列表并将其传入。

在这一行 排除 = BranchFruit.objects.filter(分支=args)

试试这个 排除 = BranchFruit.objects.filter(branch_id__in=[args])

我最终得到了以下解决方案:

def __init__(self, branch, *args, **kwargs):
    super(BranchFruitForm, self).__init__(*args, **kwargs)
    branchFruits = BranchFruit.objects.filter(branch_id=branch.id)
    excludes = [fruit.fruit.id for fruit in branchFruits]
    self.fields['fruit'].queryset = Fruit.objects.all().exclude(id__in=excludes)

非常感谢,伙计们。