我如何添加一个记录到一个表定义在django模型中包含一个content_object字段使用raw sql



我得到了一个这样定义的模型:

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一样,

相关内容

最新更新