在Django中更改选择Manytomany字段

时间:2018-10-22 14:58:50

标签: django django-models

我有一个名为alphabet的ManyToManyField,其中包含字段A,B,C和D-无论是选中还是未选中。

如何将选择字母“ A”的查询更改为“ B”?

class Alphabet(models.Model):
    id = models.AutoField(primary_key=True)
    letter = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        return self.letter

class Chapter(models.Model):
    letter = models.ManyToManyField(Alphabet, blank=True)

class Section(models.Model):
    def somefunction:
        jobs = Chapter.objects.filter(letter__letter='A')
        for i in jobs:
            #change those selected with A to B

1 个答案:

答案 0 :(得分:0)

例如,您要将字母A的Chapter对象更改为B?尝试使用update

jobs = Chapter.objects.filter(letter__letter='A')
jobs.update(letter=Alphabet.objects.get(letter='B'))