Django表单queryset:排除现有记录

时间:2015-07-24 10:15:06

标签: django forms django-queryset

在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')

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

形式:

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'

我该如何解决?

3 个答案:

答案 0 :(得分:1)

我认为它期望ID不是对象。尝试构建一个id列表并将其传入。

答案 1 :(得分:1)

在这一行     excludes = BranchFruit.objects.filter(branch = args)

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

答案 2 :(得分:0)

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

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)

非常感谢,伙计们。