【问题标题】:Get an object in a Many-to-Many Relationship in Django在 Django 中获取多对多关系中的对象
【发布时间】:2020-05-19 13:47:30
【问题描述】:

我有这两个模型:

class Instrument(MPTTModel):
    name = models.CharField(max_length=100, null=True, blank=True)
    category = models.CharField(max_length=100, null=True, blank=True)

class Instrumentation(models.Model):
    instrument = models.ManyToManyField(Instrument, verbose_name=_('instrument'), related_name='instrumentation', blank=True)

我想向 Instrument 模型添加一个 save 方法,该方法将检查 Instrumentation 是否已经有一个与当前仪器有单一关系的对象。如果没有,我将创建一个与当前仪器有一种关系的仪器对象。如果是这样,那么什么都不会发生。如果乐器有另一个与小提琴、小提琴和大提琴有关系的对象。它会忽略它。

例如。

我正在尝试保存一个名为“小提琴”的乐器对象。乐器保存方法将搜索乐器表以查看是否有乐器对象包含与小提琴的单一关系。如果它不存在,那么它将创建与“小提琴”有关系的检测对象。

我有类似的东西,但我无法正确过滤:

在仪器模型中:

def save(self, *args, **kwargs):
    try: 
        exists = Instrumentation.objects.filter(name=self.name)
    except:
        new = Instrumentation.objects.create(
            instrument=self.pk,
            name=self.name,)
        new.save()
    super().save(*args, **kwargs)

【问题讨论】:

  • 问题是在你把Instrumentation保存到数据库之前,你不能构造一个与Instrument的多对多关系,因为此时它没有主键参考。
  • 顺便说一下,根据您的模型,Instrumentation 没有 name 字段。
  • 仪器已经存在。只是尝试创建检测对象。
  • 基本上我想做的是单一乐器的音乐有单一的乐器。当我创建一个新仪器时,我想返回并按保存以创建仪器对象。有更好的方法吗?
  • 但您覆盖了Instrument 对象的save(..) 方法。所以如果self.pkNone,那就说明还没有记录。

标签: django django-models django-templates django-views django-queryset


【解决方案1】:

正如 cmets 和 docs 中提到的,在保存目标记录之前,您不能通过 M2M 关系添加记录(获取分配的 PR)。如果您确实需要创建与Instrument 同名的Instrumentation 对象并将此对象添加到Instrument,如果它仍然不存在,那么您可以这样:

如果Instrumentation 存在与否,我假设您无论如何都想保存Instument 记录:

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)

    if not Instrumentation.objects.filter(name=self.name).exists()
        instrumentation = Instrumentation.objects.create(name=self.name)
        self.instrumentation.add(instrumentation)

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2020-02-05
    • 2013-11-16
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 2021-11-25
    • 2020-09-22
    相关资源
    最近更新 更多