Django模型save()不插入新记录

时间:2023-01-29 13:51:28

I have a problem that the save method on a many to many model is not inserting into the database:

我有一个问题,即多对多模型上的save方法没有插入到数据库中:

try:
    dnpg = Device_Name_Product_Group_XREF.objects.get(device_name = dn, product_group = product_group)
except Device_Name_Product_Group_XREF.DoesNotExist:
    dnpg = Device_Name_Product_Group_XREF(device_name=dn, product_group = product_group)

    dnpg.save()

    # this prints: {'product_group': 1992L, 'device_name': 6481L}
    print model_to_dict(dnpg)

The code above should insert a record into the XREF table with values (1992,6481), but it does not. Here are my model definitions:

上面的代码应该使用值(1992,6481)将记录插入XREF表中,但事实并非如此。以下是我的模型定义:

class Device_Name_Product_Group_XREF(models.Model):
    device_name = models.ForeignKey(Device_Name, primary_key=True, to_field = "id", db_column="DEVICE_NAME_ID")
    product_group = models.ForeignKey(Product_Group, primary_key=True, to_field = "id", db_column="PRODUCT_GROUP_ID")

    class Meta:
        db_table = 'ADMIN_DEVICE_NAMES_PRODUCT_GROUP_XREF'
        managed = False

Any ideas?

有任何想法吗?

1 个解决方案

#1


1  

You can use get_or_create instead of try/except construction.

您可以使用get_or_create而不是try / except构造。

#1


1  

You can use get_or_create instead of try/except construction.

您可以使用get_or_create而不是try / except构造。