'Django: Non-primary Foreign Key object can't access related model instance

I'm new in Django. I have 2 class tech_system adn equiptment in models.py

class tech_system(models.Model):
    id_tech_system = models.BigAutoField(db_column='ID_tech_system', primary_key=True)
    system_descript_short = models.CharField(max_length=255, blank=True, null=True)
    #More field here
    tech_system_code = models.CharField(unique=True, max_length=40)

    class Meta:
        managed = False
        db_table = 'tech_system'
        
    def __str__(self):
        return self.system_descript_short

        
class equiptment(models.Model):
    id_thietbi = models.BigAutoField(db_column='ID_thietbi', primary_key=True)
    tech_system_code = models.ForeignKey('tech_system', models.DO_NOTHING, db_column="tech_system_code", blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'equiptment'

I use python shell, equiptment model object can't access to related tech_system model instance. I got the error matching query does not exist. I want to get the value obj1.equiptment.tech_system_code.system_descript_short. How can I do?

Thank you.

>>> obj1 = equiptment.objects.first()
>>> obj1.tech_system_code_id
'530'
>>> obj1.tech_system_code
Traceback (most recent call last):
  File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 173, in __get__
    rel_obj = self.field.get_cached_value(instance)
  File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\mixins.py", line 15, in get_cached_value
    return instance._state.fields_cache[cache_name]
KeyError: 'tech_system_code'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 187, in __get__
    rel_obj = self.get_object(instance)
  File "D:\Dev1\env1\lib\site-packages\django\db\models\fields\related_descriptors.py", line 154, in get_object
    return qs.get(self.field.get_reverse_related_filter(instance))
  File "D:\Dev1\env1\lib\site-packages\django\db\models\query.py", line 437, in get
    self.model._meta.object_name
app.models.tech_system.DoesNotExist: tech_system matching query does not exist.


Solution 1:[1]

I found that tech_system_code record is assigned as str type, not an object in equiptment model. Record values imported to the database is not correct. Thanks for your help.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 QuangNA