Django KeyError: 'some-ForeignKey-field-in-model'

Я очень сильно застрял на этой ошибке в течение нескольких дней, и я не могу понять, что она пытается сказать мне, так как это только 2 слова.

Ошибка возникает, когда я пытаюсь вставить данные в таблицу DB с помощью оболочки python manage.py

> from app_name.models import Usermanagement
> from app_name.models import Inquery

i = Inquery( inqueryid=6, inquerynumber="INQ765758499", sourceairportid=Airport(airportid=1), 
destinationairportid=Airport(airportid=21),  stageid=Stage(stageid=1), commoditytypeid=6, customerid=Customer(customerid=1),
branchid=1, transactiontype="AGENT", businesstype="Self", hodate="2020-11-18",  totalshipmentunits=56, 
unitid=100, grossweight=100, volumemetricweight=100, remark="test", 
dateofcreation="2018-11-20 00:00:00", dateofmodification="2018-11-20 00:00:00", 
createdby = Usermanagement(userid=0), modifiedby = Usermanagement(userid=0))

#error

KeyError: 'createdby'

#traceback

File C:\Python310\lib\site-packages\django\db\models\base.py:768, in Model.save(self, force_insert, force_update, using, update_fields)
    757 def save(
    758     self, force_insert=False, force_update=False, using=None, update_fields=None
    759 ):
    760     """
    761     Save the current instance. Override this in a subclass if you want to
    762     control the saving process.
   (...)
    766     non-SQL backends), respectively. Normally, they should not be set.
    767     """
--> 768     self._prepare_related_fields_for_save(operation_name="save")
    770     using = using or router.db_for_write(self.__class__, instance=self)
    771     if force_insert and (force_update or update_fields):

File C:\Python310\lib\site-packages\django\db\models\base.py:1092, in Model._prepare_related_fields_for_save(self, operation_name, fields)
   1087         # If the relationship's pk/to_field was changed, clear the
   1088         # cached relationship.
   1089         if getattr(obj, field.target_field.attname) != getattr(
   1090             self, field.attname
   1091         ):
-> 1092             field.delete_cached_value(self)
   1093 # GenericForeignKeys are private.
   1094 for field in self._meta.private_fields:

File C:\Python310\lib\site-packages\django\db\models\fields\mixins.py:28, in FieldCacheMixin.delete_cached_value(self, instance)
     27 def delete_cached_value(self, instance):
---> 28     del instance._state.fields_cache[self.get_cache_name()]

KeyError: 'createdby'

#models.py (только часть, для сортировки Вопрос)

# this model is in freight app
class Inquery(models.Model):
    
    inqueryid = models.BigAutoField(db_column='InqueryID', primary_key=True)
    inquerynumber = models.CharField(db_column='InqueryNumber', max_length=45)
    sourceairportid = models.ForeignKey(Airport, on_delete=models.CASCADE, db_column='SourceAirportID',related_name="Flight_inquery_source")
    destinationairportid = models.ForeignKey(Airport, on_delete=models.CASCADE, db_column='DestinationAirportID',related_name="Flight_inquery_destination")
    stageid = models.ForeignKey('Stage', on_delete=models.CASCADE, db_column='StageID')
    commoditytypeid = models.IntegerField(db_column='CommodityTypeID')
    customerid = models.ForeignKey(Customer, on_delete=models.CASCADE, db_column='CustomerID')
    branchid = models.IntegerField(db_column='BranchID')
    transactiontype = models.CharField(db_column='TransactionType', max_length=10)
    businesstype = models.CharField(db_column='BusinessType', max_length=15)
    hodate = models.DateTimeField(db_column='HODate')
    totalshipmentunits = models.CharField(db_column='TotalShipmentUnits', max_length=20)
    unitid = models.CharField(db_column='UnitID', max_length=3)
    grossweight = models.FloatField(db_column='GrossWeight')
    volumemetricweight = models.FloatField(db_column='VolumemetricWeight')
    remark = models.CharField(db_column='Remark', max_length=8000)
    dateofcreation = models.DateTimeField(db_column='DateOfCreation')
    dateofmodification = models.DateTimeField(db_column='DateOfModification')
    createdby = models.ForeignKey('accounts.Usermanagement', on_delete=models.CASCADE, db_column='CreatedBy', to_field='createdby',related_name="Usermanagement_Inquery_createdby")
    modifiedby = models.ForeignKey('accounts.Usermanagement', on_delete=models.CASCADE, db_column='ModifiedBy', to_field='modifiedby',related_name="Usermanagement_Inquery_modifiedby")
    isactive = models.IntegerField(db_column='IsActive')

    def __str__(self):
        return self.inquerynumber

    class Meta:
        managed = False
        db_table = 'Inquery'

#другая модель приложения

class Usermanagement(AbstractBaseUser):
    userid = models.BigAutoField(db_column='UserID', primary_key=True)
    emailid = models.CharField(db_column='EmailID', unique=True, max_length=45)
    roleid = models.ForeignKey(Role, on_delete=models.CASCADE, db_column='RoleID')
    organizationid = models.ForeignKey(Organization, on_delete=models.CASCADE, db_column='OrganizationID')
    firstname = models.CharField(db_column='FirstName', max_length=45)
    middlename = models.CharField(db_column='MiddleName', max_length=45, blank=True, null=True)
    lastname = models.CharField(db_column='LastName', max_length=45, blank=True, null=True)
    numberofretry = models.IntegerField(db_column='NumberOfRetry',default=0)
    timeoffset = models.CharField(db_column='TimeOffSet', max_length=6,default="+5:30")
    password = models.CharField(db_column='Password', max_length=45)
    passwordexpirydate = models.DateTimeField(db_column='PasswordExpiryDate',default='2022-12-30 12:30:59')
    dateofcreation = models.DateTimeField(db_column='DateOfCreation',auto_now_add = True)
    dateofmodification = models.DateTimeField(db_column='DateOfModification',auto_now = True)
    createdby = models.BigIntegerField(db_column='CreatedBy',unique=True) #this field is FK in many other models
    modifiedby = models.BigIntegerField(db_column='ModifiedBy',unique=True) #this field is FK in many other models
    isactive = models.BooleanField(db_column='IsActive',default=1)

    last_login = False

    objects = UsermanagementCustomUserManager()

    USERNAME_FIELD = "emailid"
    EMAIL_FIELD = "emailid"
    REQUIRED_FIELDS = ["roleid","organizationid","firstname","passwordexpirydate","createdby","modifiedby"]


    def __str__(self):
        return self.emailid
--------------------- some more code ------------------

Вы, вероятно, хотите использовать Usermanagement.objects.get(userid=0) вместо Usermanagement(userid=0) Чтобы получить существующий внешний ключ и не создавать экземпляр пользователя, не сохраненного в базе данных и, следовательно, недоступного

как ответил @vctrd

Мой запрос теперь такой: Inquery ( inqueryid=6, inquerynumber="INQ765758499", sourceairportid=Airport(airportid=1), destinationairportid=Airport(airportid=21), stageid=Stage(stageid=1), commoditytypeid=6, customerid=Customer(customerid=1), branchid=1, transactiontype="AGENT", businesstype="Self", hodate="2020-11-18", totalshipmentunits=56,unitid=100, grossweight=100, volumemetricweight=100,remark="test", dateofcreation="2018-11-20 00: 00:00", dateofmodification="2018-11-20 00:00:00", createdby = Usermanagement. objects.get(userid=0), modifiedby = Usermanagement.objects.get(userid=0), isactive=1)

Вернуться на верх