gpt4 book ai didi

python - 使用信号检测 Django 中的保存操作时对象中未显示多对多字段

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:52 25 4
gpt4 key购买 nike

这是一个跟进问题:Cant get post_save to work in Django

我的模型是:

class Car(models.Model):
name = models.CharField(max_length=50)
...
some other attributes of Car
...

class Person(models.Model):
car = models.ManyToManyField(Car)
name = models.CharField(max_lenght=100)
...
Some other attributes of Person
...


class License(models.Model):
person = models.ForeignKey(Person)
...
Other attributes of License
...

信号处理器:

def signal_handler(sender, **kwargs):
print 'Person saved!'
generate_license()

post_save.connect(signal_handler, sender=Person, dispatch_uid="Unique person")

意图:创建 Person 的实例时,我想生成一个 License 对象。所以我过滤掉添加到 License 中的最后一个元组,然后使用它的内容生成一个 License 实例。

def generate_license():
import pdb
pdb.set_trace()
man = Person.objects.filter().order_by('-time_added')[:1][0] # Restricting the filter to one query and then taking the value at the 0th index. order_by '-time_added' gives the latest tuple at the top.
license = License.objects.create(...Info about car, person...)

错误:

一个例子:假设 Car 有 3 个实例:

  1. 宝马
  2. 法拉利
  3. 兰博基尼

现在,当我从管理员添加一个 Person 实例时,示例:

percar = BMW, FERRARIname = Bob 的实例当我在管理中单击 save 时,set_trace() 开始。所以在 generate_license 查询之后:

pdb 中,当查询执行时,我尝试打印出 per.car.all() 但它给了我 [] 和当我尝试打印出 per.name 时,它确实打印出了 Bob。所以我不太明白 per.name 是如何保存的,而 per.car 不是。

此外,当请求完成时,即我在 pdb 中按下了 c,我再次为同一个实例单击保存,这次它读取 per.car.all() 完美,而如果在保存之前,我添加了 LAMBORGHINI,它只显示 BMWFERRARI。所以我猜正在发生的事情是 many-to-many 字段来晚了。虽然我不能指出其中的原因。需要一些帮助。我错过了什么吗?

问题:是否有特定的方法从创建信号中识别更新信号?我的意思是我不想在每次更新数据时都生成一个新的 License。新的 License 只会在数据创建后生成。那么,如何区分updatesave信号呢?

最佳答案

post_save 不适用于 m2m 字段。你必须使用 m2m_changed signal .

像这样:

def my_m2m_signal(sender, **kwargs):
action = kwargs.get('action')
if action == 'post_add':
print 'post_add is activated on m2m'

signals.m2m_changed.connect(my_m2m_signal, sender=Person.car.through)

关于python - 使用信号检测 Django 中的保存操作时对象中未显示多对多字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17263780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com