gpt4 book ai didi

mysql - Django 完整性错误 - id 不能为空

转载 作者:行者123 更新时间:2023-11-29 13:22:07 24 4
gpt4 key购买 nike

我知道这个问题以前已经被回答过,但我已经浏览了每个答案,但没有任何意义,或者我觉得我的代码已经在做答案中所说的事情。

所以我有一个术语和链接的模型,它具有多对多的关系。

class ProjectTerms(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
terms = models.CharField(max_length=100)

class Meta:
db_table = 'project_terms'

class ProjectLinks(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
links = models.CharField(max_length=100)
relations = models.ManyToManyField(ProjectTerms)

class Meta:
db_table = 'project_links'

class ProjectLinksRelations(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
project_terms = models.ForeignKey('ProjectTerms')
project_links = models.ForeignKey(ProjectLinks)

脚本:

def create_models(my_term, my_link):
saved_term = ProjectTerms.objects.update_or_create(terms = my_term)
saved_link = ProjectLinks.objects.update_or_create(links = my_link)

ProjectLinksRelations.objects.update_or_create(project_terms=saved_term, project_links=saved_link)

很多地方都说模型(这里的术语和链接)必须在添加到连接数据库之前保存。

我还尝试单独创建每个术语和链接并像这样保存它们:

def create_models(my_term, my_link):
saved_term = ProjectTerms(terms = my_term)
saved_term.save()
saved_link = ProjectLinks(links = my_link)
saved_link.save()

relation = ProjectLinksRelations.objects.update_or_create(project_terms=saved_term, project_links=saved_link)
relation.save()

最佳答案

您所需要的只是:

class ProjectTerms(models.Model):
terms = models.CharField(max_length=100)

class ProjectLinks(models.Model):
links = models.CharField(max_length=100)
relations = models.ManyToManyField(ProjectTerms)

将自动创建 ManyToManyField 的 ID 字段和表。

要设置ManyToMany关系,请使用add:

def create_models(my_term, my_link):
(saved_term, created) = ProjectTerms.objects.update_or_create(terms = my_term)
(saved_link, created) = ProjectLinks.objects.update_or_create(links = my_link)
saved_link.relations.add(saved_term)
saved_link.save()

关于mysql - Django 完整性错误 - id 不能为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20670912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com