简体   繁体   English

django,表继承:插入数据

[英]django, table inheritance: insert data

I have these tables: 我有这些表:

class OpeDatos(models.Model):
    id_dato = models.IntegerField(primary_key=True)
    id_usuario = models.ForeignKey(SisUsuarios, db_column='id_usuario')
    id_region = models.ForeignKey(SisRegiones, db_column='id_region')
    titulo = models.CharField(max_length=70, blank=True)
    class Meta:
        managed = False
        db_table = 'ope_datos'

class OpeProductos(OpeDatos):
    id_producto = models.IntegerField(primary_key=True)
    iddato = models.OneToOneField(OpeDatos, primary_key=True, db_column="id_dato",   parent_link=True)
    id_producto_tipo = models.ForeignKey(DefProductosTipos, db_column='id_producto_tipo')
    class Meta:
         managed = False
         db_table = 'ope_productos'

I want to insert data : 我想插入数据:

from apps.inicio.models import SisUsuarios, SisRegiones, OpeDatos

usuario = SisUsuarios.objects.get(pk=1)
region = SisRegiones.objects.get(pk=1)
datos = OpeDatos()
datos.id_usuario = usuario
datos.id_region = region     
datos.save()
producto = OpeProductos() 
producto.iddato = datos.id_dato
producto.save()

displays this message: 显示此消息:

ValueError at /productos/add/ / productos / add /中的ValueError

Cannot assign None: "OpeProductos.iddato" does not allow null values. 无法分配无:“ OpeProductos.iddato”不允许为空值。

can you help me, please. 你能帮我吗。

When creating an id manually you should use AutoField instead of IntegerField 手动创建ID时,应使用AutoField而不是IntegerField

id_dato = models.AutoField(primary_key=True)

https://docs.djangoproject.com/en/1.6/ref/models/fields/#autofield https://docs.djangoproject.com/en/1.6/ref/models/fields/#autofield

What is happening is that since you are not explicitly defining the 'datos' object's id it doesnt have one, and then producto complains because the key can't have an empty value. 发生的事情是,由于您没有明确定义'datos'对象的ID,因此它没有一个ID,然后producto抱怨,因为键不能有空值。

AutoField should fix this AutoField应该解决此问题

I am surprised it doesn't fail at the earlier line: datos.save() because you have not supplied a value for the primary key datos.id_dato 我很惊讶它不会在前面的行中失败: datos.save()因为您没有提供主键datos.id_dato的值

Normally in Django you would need to use an AutoField to get an auto-incrementing primary key. 通常,在Django中,您需要使用AutoField来获取自动递增的主键。

Also you should not be specifying primary_key=True on the OpeProductos.iddato field, you can only have one primary key per model. 另外,您不应该在OpeProductos.iddato字段上指定primary_key=True ,每个模型只能有一个主键。

Then the error you are seeing is due to the fact that datos.id_dato is None since you did not provide any value for it before saving the datos instance. 然后,您看到的错误是由于datos.id_datoNonedatos.id_dato是因为在保存datos实例之前未提供任何值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM