Этот код будет выполняться нормально, но записи 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