Django:保存后访问ManyToManyField对象 [英] Django: accessing ManyToManyField objects after the save
问题描述
这让我感到困惑...当我保存我的模型时,书对象没有改变。但如果我打开发票并再次保存,则进行更改。我做错了什么?
This is baffling me... When I save my model, the book objects are unchanged. But if I open the invoice and save it again, the changes are made. What am I doing wrong?
class Invoice(models.Model):
...
books = models.ManyToManyField(Book,blank=True,null=True)
...
def save(self, *args, **kwargs):
super(Invoice, self).save(*args, **kwargs)
for book in self.books.all():
book.quantity -= 1
if book.quantity == 0:
book.sold = True;
book.save()
编辑:尝试使用post_save信号,但它的工作方式相同。第一次保存没有更改,第二次保存更改。
I've tried using the post_save signal, but it works the same way. No changes on the first save, changes saved the second time.
更新:似乎需要使用以下代码解决:
Update: Seems to be solved with this code:
class InvoiceAdmin(admin.ModelAdmin):
...
def save_model(self, request, obj, form, change):
obj.save()
for bk in form.cleaned_data['books']:
book = Book.objects.get(pk=bk.id)
book.quantity -= 1
if book.quantity == 0:
book.sold = True;
book.save()
推荐答案
我如何解决这个,确实令人困惑的行为。将信号接收器连接到models.signals.m2m_changed事件,每次更改m2m字段时触发此获取。内部评论解释为什么。$ /
This is how I worked around this, indeed baffling, behavior. Connect a signal receiver to models.signals.m2m_changed event, this get's triggered each time a m2m field is changed. The inline comments explain why.
class Gig(models.Model):
def slugify(self):
# Add venue name, date and artists to slug
self.slug = slugify(self.venue.name) + "-"
self.slug += self.date.strftime("%d-%m-%Y") + "-"
self.slug += "-".join([slugify(artist.name) for artist in self.artists.all()])
self.save()
@receiver(models.signals.m2m_changed, sender=Gig.artist.through)
def gig_artists_changed(sender, instance, **kwargs):
# This callback function get's called twice.
# 1 first change appears to be adding an empty list
# 2nd change is adding the actual artists
if instance.artist.all() and not instance.slug:
instance.slugify()
这篇关于Django:保存后访问ManyToManyField对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!