1

这是我保存模型的 Django 源代码。

e = Element(title = title, description = des, location = city, date = timezone.now())
e.save()

这是我的mysql触发器。

DELIMITER $$
CREATE TRIGGER `ins_blog` AFTER INSERT ON `blog`
 FOR EACH ROW BEGIN
    INSERT INTO snippet
    SET 
        id = LAST_INSERT_ID(`id`),
        title = NEW.title,
        snippet = NEW.description,
        source_site = 'KJOBUS',
        location = NEW.location,
        date = NEW.date;
END$$
DELIMITER ;

没有触发器,它工作正常。我可以保存。在 mysql 中,触发器工作正常,没有任何错误或警告。

但是,当我尝试通过 Django 保存数据时,会出现警告。

Exception Type: Warning
Exception Value:    
Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT. Statement is unsafe because it invokes a trigger or a stored function that inserts into an AUTO_INCREMENT column. Inserted values cannot be logged correctly.
Exception Location: /usr/lib/python2.7/dist-packages/MySQLdb/cursors.py in _warning_check, line 92
Python Executable:  /usr/bin/python

哪里没有办法在 django 中使用触发器插入数据?

4

1 回答 1

0

用 Django 信号替换 Mysql 触发器

您可以使用 Django 的 post_save 信号来替换您的 mysql 触发器。以下是完全等价的。

from django.signals import post_save
from django.dispatch import receiver

@reciever(post_save, sender=Element) # or sender=Blog, your example is unclear
def create_snippet(sender, instance, created, raw, **kwargs):
    if created and not raw: # raw=True when loading from fixtures
        Snippet.objects.create(
            title=instance.title,
            description=instance.description,
            source_site='KJOBUS',
            location=instance.description,
            date=instance.date,
        )

参考:https ://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.post_save

于 2013-11-18T00:00:26.247 回答