我得到了一个这样定义的模型:
class LogEntry(models.Model):
text = models.CharField(max_length = 20)
content_type = models.ForeignKey(ContentType, null=True, blank=True)
object_id = models.PositiveIntegerField(null=True, blank=True)
content_object = generic.GenericForeignKey('content_type', 'object_id')
from django.contrib.auth.models import User
usr = User.objects.all()[0]
new_record = LogEntry.objects.create(text="foobar", content_object=usr)
但是我如何使用普通SQL创建相同的记录?问题当然是如何确定如何在content_type和content_object字段中插入值。
from django.db import connection, transaction
cursor = connection.cursor()
cursor.execute("""
insert into appname_log_entry SET (text, content_type, object_id)
calues(%s, %s, %s)""",
['foobar', <how to get content type?>, ModelInstance.Id])
我必须设置content_objet吗?如果有,那是怎么回事?
我不明白你为什么要这样做。
在任何情况下,content_type
字段只是一个标准的外键。所以你可以通过model_instance.content_type_id
得到它的ID和其他FK ID一样,