gpt4 book ai didi

python - 多对多关系 禁止直接分配到多对多集合的前向端

转载 作者:太空宇宙 更新时间:2023-11-03 19:43:28 24 4
gpt4 key购买 nike

我创建了一些模型,其中一个具有多对多关系。

class PBSItems(models.Model):
PBSCode = models.CharField(max_length=6, primary_key=True)
RestrictFlag = models.CharField(max_length=1)
eAuthQuant = models.TextField()

def __str__(self):
return self.PBSCode

class Restrictions(models.Model):
IndicatId = models.IntegerField(primary_key=True)
RestrictFullText = models.CharField(max_length=17040)

def __str__(self):
return self.IndicatId

class Drug(models.Model):
PBSCode = models.ForeignKey(PBSItems, null=True, on_delete = models.CASCADE)

def __str__(self):
return self.PBSCode

class Links(models.Model):
PBSCode = models.ManyToManyField(Drug)
IndicatId = models.ForeignKey(Restrictions, on_delete = models.CASCADE)

def __str__(self):
return self.IndicatId

但是,一旦我为 PBSItems、限制和药物创建实例,并尝试为链接创建实例,我会收到以下消息:

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use PBSCode.set() instead.

如何在模型中使用 PBSCode.set(),或者如何解决此问题?

非常感谢

编辑:

我正在使用管理命令来创建实例

加载链接

from csv import DictReader
import csv, os
from datetime import datetime
from django.core.management.base import BaseCommand
from myapp.models import Links, PBSItems
from pytz import UTC

class Command(BaseCommand):

def handle(self, *args, **kwargs):
now = datetime.now()
yearid=str(now.year)
monthid= now.month
if monthid<10:
monthid="0"+str(monthid)
else:
monthid=str(monthid)
fN_Link = os.path.join("data - "+yearid+monthid+"01"+"\\LinkExtract_"+yearid+monthid+"01.txt")
print(fN_Link)
with open(fN_Link) as file:
Link_reader = csv.reader(file, delimiter='\t')
for row in Link_reader:
links = Links()
if row != []:
links.PBSCode, _ = PBSItems.objects.get_or_create(PBSCode = row[0])
links.IndicatId = row[1].strip()
links.save()
self.stdout.write(self.style.SUCCESS('Data imported successfully'))

加载限制

from csv import DictReader
import csv, os
from datetime import datetime
from django.core.management.base import BaseCommand
from myapp.models import Restrictions
from pytz import UTC

class Command(BaseCommand):

def handle(self, *args, **kwargs):
now = datetime.now()
yearid=str(now.year)
monthid= now.month
if monthid<10:
monthid="0"+str(monthid)
else:
monthid=str(monthid)
fN_Restrict = os.path.join("data - "+yearid+monthid+"01"+"\\RestrictionExtract_"+yearid+monthid+"01.txt")
print(fN_Restrict)
with open(fN_Restrict) as file:
Restrict_reader = csv.reader(file, delimiter='\t')
for row in Restrict_reader:
restrict = Restrictions()
if row != []:
restrict.IndicatId1 = row[0]
restrict.RestrictFullText = row[1]
restrict.save()
self.stdout.write(self.style.SUCCESS('Data imported successfully'))

加载_PBS_项目

from csv import DictReader
import csv, os
from datetime import datetime
from django.core.management.base import BaseCommand
from myapp.models import PBSItems, PrescriberType, Note, Caution
from pytz import UTC
import pandas as pd

class Command(BaseCommand):

def handle(self, *args, **kwargs):
now = datetime.now()
yearid=str(now.year)
monthid= now.month
if monthid<10:
monthid="0"+str(monthid)
else:
monthid=str(monthid)
fN_PBSItems = os.path.join("data - "+yearid+monthid+"01"+"\\PBS_Item_Table_"+yearid+monthid+"01.txt")
print(fN_PBSItems)
df=pd.read_csv(fN_PBSItems,sep='\t', header=None)
df.columns = ['PBSCode']
df = df[df['EndDate'] ==' ']
for index, row in df.iterrows():
pbsitems = PBSItems()
pbsitems.PBSCode = row[0]
pbsitems.RestrictFlag = row[1]
pbsitems.eAuthQuant = row[2]
pbsitems.save()
self.stdout.write(self.style.SUCCESS('Data imported successfully'))

加载药物

from csv import DictReader
import csv, os
from datetime import datetime

from django.core.management.base import BaseCommand

from myapp.models import Drug, PBSItems, Manfr, ATC
from pytz import UTC

class Command(BaseCommand):

def handle(self, *args, **kwargs):
now = datetime.now()
yearid=str(now.year)
monthid= now.month
if monthid<10:
monthid="0"+str(monthid)
else:
monthid=str(monthid)
fN_Drug = os.path.join("data - "+yearid+monthid+"01"+"\\drug_"+yearid+monthid+"01.txt")
print(fN_Drug)
with open(fN_Drug) as file:
Drug_reader = csv.reader(file, delimiter='!')
for row in Drug_reader:
drug = Drug()
if row != []:
drug.ProgramCode = row[0]
drug.PBSCode, _ = PBSItems.objects.get_or_create(PBSCode = row[1])
drug.save()
self.stdout.write(self.style.SUCCESS('Data imported successfully'))

编辑(2):对 LoadLinks 的建议更改

from csv import DictReader
import csv, os
from datetime import datetime
from django.core.management.base import BaseCommand
from myapp.models import Links, PBSItems, Restrictions
from pytz import UTC

class Command(BaseCommand):

def handle(self, *args, **kwargs):
now = datetime.now()
yearid=str(now.year)
monthid= now.month
if monthid<10:
monthid="0"+str(monthid)
else:
monthid=str(monthid)
fN_Link = os.path.join("data - "+yearid+monthid+"01"+"\\LinkExtract_"+yearid+monthid+"01.txt")
print(fN_Link)
with open(fN_Link) as file:
Link_reader = csv.reader(file, delimiter='\t')
for row in Link_reader:
links = Links()
if row != []:
pbs_items, _ = PBSItems.objects.get_or_create(PBSCode = row[0])
links.PBSCode.append(pbs_items)
links.IndicatId = row[1].strip()
links.save()

链接模型的更改

class Links(models.Model):
PBSCode = models.ForeignKey(Drug, on_delete = models.PROTECT, null = True)
#PBSCode = models.ManyToManyField(Drug)
IndicatId = models.ForeignKey(Restrictions, on_delete = models.CASCADE)

def __str__(self):
return self.IndicatId

最佳答案

你有:

links.PBSCode, _ = PBSItems.objects.get_or_create(PBSCode = row[0])

您需要将新创建的 PBSItems 实例附加或设置到 links.PBSCode

pbs_items, _ = PBSItems.objects.get_or_create(PBSCode = row[0])
links.PBSCode.append(pbs_items)
# Or if you want to reset the whole relationship to just this one instance
links.PBSCode.set([pbs_items])

此外,行业最佳实践是使用蛇形命名字段,例如 links.pbs_code。以及在有意义的情况下将模型命名为其唯一实例。因此,PBSItems 将是 PBSItemLinksLink。最后,在命名外键关系时,如果没有必要,最好不要使用 Id 后缀,因为当您访问该属性时,它会为您提供该关系的实例。因此 Link.IndicatId 将变为 Link.indicat

关于python - 多对多关系 禁止直接分配到多对多集合的前向端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60292637/

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