python - Model.ManyToManyField.all() 给出 AttributeError : 'ManyToManyDescriptor' object has no attribute 'all'

标签 python django attributeerror manytomanyfield django-2.0

我正在使用 Django 2.0.2、Python 3.6.4 和 PyCharm 2017.3.3

模型:(在 models.py 中)

class Position(models.Model):
    title = models.CharField(max_length=50)
    gang = models.ForeignKey(Gang, on_delete=models.CASCADE)
    description = models.TextField(max_length=20000)

    def __str__(self):
        return str(self.title) + ', ' + str(self.gang)

class Application(models.Model):
    positions = models.ManyToManyField(Position)
    applicant = models.ForeignKey(User, on_delete=models.CASCADE)

class Ranking(models.Model):
    position = models.ForeignKey(Position, on_delete=models.CASCADE)
    applicant = models.ForeignKey(User, on_delete=models.CASCADE)
    rank = models.IntegerField(default=3,validators=[
            MaxValueValidator(3),
            MinValueValidator(1)
        ])

表单:(在 forms.py 中)

class RankingForm(forms.ModelForm):
    rank = forms.IntegerField(max_value=3, min_value=1)
    position = forms.ModelMultipleChoiceField(queryset=Application.positions.all())

    class Meta:
        model = Ranking
        exclude = ['applicant']
        fields = ('rank', 'position')

    def __init__(self, *args, **kwargs):
        super(RankingForm, self).__init__(*args, **kwargs)
        self.fields['rank'].widget.attrs.update({'class': 'form-control'})

我不断收到 RankingForm 中的 AttributeError

“position = forms.ModelMultipleChoiceField(queryset=Application.positions.all())”

当我写作时

class Application(models.Model):
    ... 

    def __str__(self):
        return str(self.positions.all())

它在 django-admin 中显示为查询集(适用于 forms.ModelMultipleChoiceField()),但写入

    class Application(models.Model):
    ... 

    def __str__(self):
        return str(Application.positions.all())

给了我同样的错误:“ManyToManyDescriptor”对象没有属性“all”

写作

    class RankingForm(forms.ModelForm):
        ...
        position = forms.ModelMultipleChoiceField(queryset=Position.objects.all())

有效,但这不是我想要该字段显示的内容。

我想用特定应用程序中的所有位置创建一个 ModelMultipleChoiceField(),但这个错误一直在阻碍。看来仅仅引用一个模型是不行的,但是引用 self 可以吗?任何帮助是极大的赞赏! :)

顺便说一句,我还没有找到关于这个问题的任何好的文档,但是 this似乎是 ManyToManyDescriptor 所在的 related_descriptors.py 的代码

最佳答案

评估关系是通过作为类的初始化实例的实例来完成的。

应用程序的实例。

application = Application.objects.first()
application.positions.all()

初始化后更改表单查询集。

class RankingForm(forms.ModelForm):
    rank = forms.IntegerField(max_value=3, min_value=1)
    position = forms.ModelMultipleChoiceField(queryset=Positions.objects.none())

    class Meta:
        model = Ranking
        exclude = ['applicant']
        fields = ['rank', 'position']

    def __init__(self, *args, **kwargs):
        super(RankingForm, self).__init__(*args, **kwargs)
        self.fields['rank'].widget.attrs.update({'class': 'form-control'})  
        self.fields['position'].queryset = self.instance.positions.all()

关于python - Model.ManyToManyField.all() 给出 AttributeError : 'ManyToManyDescriptor' object has no attribute 'all' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49481650/

相关文章:

javascript - 查找缩小的 Javascript 中的错误位置

python - AttributeError: LinearRegression 对象没有属性 'coef_'

python - 输出不平衡时的神经网络回归

python - 用 pyspark 替换数据框中一列的所有值

python - Django - 创建多个文件的 Zip 并使其可下载

python - 带有排除和注释的 Django QuerySet 不返回任何结果

python - AttributeError: 'module' 对象没有属性 'config'

python - 使用指数减法评估 symfit 模型时的 AttributeError

python - 为什么这个 Python 脚本在多核上的运行速度比在单核上慢 4 倍

python - 每列的 django 计数