此代码将正常执行,但foreignkey
记录将不会保存在数据库中:
new_org, created = models.Organization.objects.get_or_create(symbol = row['Symbol'], batch=batch_id)
new_org.industry, created = models.DictIndustry.objects.get_or_create(value=row['industry'], batch=batch_id)
new_org.sector, created = models.DictSector.objects.get_or_create(value=row['Sector'], batch=batch_id)
new_org.save()
print(new_org.__dict__)
输出已分配了industry
和sector
:
{'_state': <django.db.models.base.ModelState object at 0x1142d0748>,
'id': 3152,
'date_created': datetime.datetime(2019, 2, 7, 21, 36, 55, 883816, tzinfo=<UTC>), 'date_updated': None,
'generation': 1,
'batch': 0,
'symbol': 'DDD',
'industry': <DictIndustry: Computer Software: Prepackaged Software>,
'sector': <DictSector: Technology>}
但是数据库将没有这些记录:
id | date_created | date_updated | generation | batch | symbol | industry_id | sector_id
------+-------------------------------+--------------+------------+-------+--------+-------------+-----------
3152 | 2019-02-07 16:36:55.883816-05 | | 1 | 0 | DDD | |
industry
和sector
的记录都可以很好地沉入数据库(postgresql)。
我怀疑这与我对模型进行编码的方式有关,但是我无法发现任何可能破坏它的东西。 PostgreSQL是否有任何特定原因可能导致这种情况?
class BaseModel(models.Model):
date_created = models.DateTimeField(auto_now=True)
date_updated = models.DateTimeField(null=True, blank=True)
generation = models.IntegerField(default=DATA_GENERATION)
batch = models.IntegerField()
class Meta:
abstract = True
class AttributeBase(BaseModel):
source = models.CharField(max_length=16, blank=False, null=False)
def __str__(self):
if hasattr(self, 'value'):
return self.value
raise NotImplementedError("value field not implemented for this model and it should have been")
class Meta:
abstract = True
unique_together = ('source', 'parent', 'value', 'generation')
class DictBase(BaseModel):
value = models.CharField(max_length=128, unique=True)
class Meta:
abstract = True
def __str__(self):
if hasattr(self, 'value'):
return self.value
raise NotImplementedError("value field not implemented for this model and it should have been")
class DictSector(DictBase):
pass
class DictIndustry(DictBase):
pass
class Organization(BaseModel):
symbol = models.CharField(unique=True, max_length=12, null=False, blank=False)
sector = models.ForeignKey(DictSector, on_delete=models.DO_NOTHING, null=True, blank=True)
industry = models.ForeignKey(DictIndustry, on_delete=models.DO_NOTHING, null=True, blank=True)
def __str__(self):
return self.symbol
答案 0 :(得分:0)
这与django无关,并且django可以正常工作。以防万一它可以帮助某人。如果您在Jupyter之类的笔记本中运行与Django相关的代码,请不要忘记重新加载内核以随身携带您正在制作的模型中的更改。
(我尝试自动重新加载,但对我来说效果不佳)。