【问题标题】:Django: Auto populate m2m field of a modelDjango:自动填充模型的 m2m 字段
【发布时间】:2021-03-16 14:04:09
【问题描述】:

我有一个类别类型的模型(称为标签):

class Tag(models.Model):
    name = models.CharField(...)
    slug = models.SlugField(unique=True)
    #...

在另一个模型中用作 m2m 字段:

class Order(models.Model):
    user = models.ForeignKey(...)
    type = models.CharField(...)
    tag = models.ManyToManyField(Tag, blank=True)

现在,假设创建了一个订单并且程序想要自动为其分配一些标签。比如说,程序想要将Order.type 添加到它的Order.tag 列表中。 (假设Order.type 恰好与有效的Tag.name 相同) 我试过订单的post_save 没有运气:

def order_post_save_reciever(sender, instance, *args, **kwargs):
    #..., disconnect, ...
    instance.tag.add(Tag.objects.filter(name=instance.type))
    instance.save()
    #.... reconnec, t.....

Apparently,我必须使用signals,但我不知道如何。你知道如何在这里添加标签吗? 非常感谢您的帮助。

【问题讨论】:

  • 为什么必须使用信号?不是两个模型都在你自己的项目中吗?另外,您链接的答案显然还没有阅读,因为它明确声明不要使用post_save
  • @Melvyn 也许我没有正确解释。是的,我阅读了链接并意识到post_save 不是正确的地方。此外,我不知道是否/如何使用该信号。这就是我问的原因:)。我猜是你没有正确阅读问题。你的解决方案是什么? (如果你知道的话)。毕竟,这就是我们所追求的。
  • 如果我的两个都是我的模型,我的解决方案是不使用信号。如果您保存订单,您可以在其保存方法中添加标签。为什么要使用信号?事实上,如果 Order 是我的模型,我不在乎 Tag 是谁的模型,我不必使用信号。

标签: django django-models


【解决方案1】:

删除 instance.save(),因为它会创建一个循环。

【讨论】:

  • 为了减少不相关的代码,这里没有显示断开和重新连接线。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 2018-12-22
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-22
相关资源
最近更新 更多