Queryset Item pk doesn't match pk of indexed item

This is really strange, and I’ve never had this issue before. Here’s a basic layout of my models (pseudocode):

class Part(models.Model):
    number = CharField()
    name = CharField()

class Transaction(models.Model):
    qty = FloatField()
    date = DateField()

class LineItem(models.Model):
    transaction = ForeignKey(Transaction)
    part = ForeignKey(Part)

I run this command on a specific part:

>>> p = Part.objects.get(pk=29658)
>>> lis = p.lineitems.all()
<QuerySet [<LineItem: 61067 - 1.0 -  2020-01-10 06:00:00>, <LineItem: 61067 - 1.0 - 2020-01-10 15:44:42.948797>, <LineItem: 61067 - 1.0 - 2019-01-07 06:00:00>, <LineItem: 61067 - 1.0 - 2019-03-26 16:34:42.827122>, <LineItem: 61067 -1.0 - 2019-03-26 05:00:00>]>

Notice how I get 5 distinct line items. I kept getting an error on this part, and I can’t figure out why it’s getting the error. Observe:

>>> lis[0]
<LineItem: 61067 - 1.0 - 2020-01-10 06:00:00>
>>> lis[1]
<LineItem: 61067 - 1.0 - 2020-01-10 06:00:00>
>>> lis[0].pk
497039
>>> lis[1].pk
497039
>>> lis[2]
<LineItem: 61067 - 1.0 - 2019-01-07 06:00:00>
>>> lis[0]==lis[1]
True
>>> lis[0]==lis[2]
False
>>> lis[0]==lis[3]
False
>>> lis[1]==lis[4]
False

For some very strange reason, when I retrieve the indexed value, the first and second elements are equal. I have tried this in a new session to clear the Query cache, but I get the same results.

I’m using Postgres. I’m wondering if this goes deeper, but I just don’t know. The print of the QuerySet results shows the correct instances. It’s when I start diving into them that they are different than what they say they are. I would appreciate your help.

If I print the li pks in a loop:

for li in lis:
… print(f"{li.transaction_id}")

497039
497050
438586
445406
445390

for index, e in enumerate(lis):
… print(f"{lis[index].pk}")

497039
497050
438586
445406
445390

There’s not quite enough information here to perform any real diagnosis, but if I had to look into this, I’d start with examining the data. In this case, rather than trying to browse tables using something like pgadmin, I’d dump the data using, appropriately enough, the dumpdata command. That’ll give you a JSON representation of your tables that you can use to verify that the foreign keys and data are what you think they should be. I’d also look at the schema to verify that your LineItem table has a proper primary key defined at the database level.