I have a Django project in which I am using a SQLLite database as the backend data source.
In my model I have the following objects and use the AutoCreated id field as the Primary Key:
class EquipmentModel(models.Model):
Name = models.CharField(max_length=255)
Description = models.CharField(max_length=255)
class EquipmentTagsModel(models.Model):
Equipment = models.ForeignKey(‘EquipmentModel’,on_delete=models.PROTECT)
TagName = models.CharField(max_length=255)
TagType = models.CharField(max_length=255)
The schema is built and the data is populated by using Python migrations, one of which runs a SQL file to insert data into the tables.
After migratinging, if I query api_equipmentmodel in VSCode/SQLLite Explorer, I see the following rows:
id | Name | Description |
---|---|---|
1 | Eq1 | Compressor 1 |
2 | Eq2 | Compressor 2 |
3 | Eq3 | Compressor 3 |
If I query api_equipmenttagsmodel, I see the following rows:
id | Equipment_id | TagName | TagType |
---|---|---|---|
1 | 1 | Pressure | Float |
2 | 1 | Flow | Float |
3 | 1 | Temperature | Float |
4 | 2 | Pressure | Float |
5 | 2 | Flow | Float |
6 | 2 | Temperature | Float |
7 | 3 | Pressure | Float |
8 | 3 | Flow | Float |
9 | 3 | Temperature | Float |
In my views.py file I have the following code:
target = "Eq2"
equipment_object = EquipmentModel.objects.filter(Name=target).first()
equipment_tags_query_set = EquipmentTagsModel.objects.filter(Equipment=equipment_object.pk)
When I execute the EquipmentModel query I find that the equipment_object.Name ="Eq2" as I expected but that that equipment_object.pk value is 1 instead of 2. Consequently, when I execute the EquipmentTagsModel query with the equipment_object.pk as the filter, I am getting rows 1-3 from the equipment_tags instead of rows 4-6 as desired.
My question is, for “equipment_object = EquipmentModel.objects.filter(Name=target).first()”, why is the equipment_object.pk return value 1 and not 2?