0

I am getting all related records using user.companies.all().

But this query is giving me random records from the userProfile_companies table. I need the order in which the records are added in the bridging table. models.py

class UserProfile(models.Model):
    companies = models.ManyToManyField('Company', blank=True, null=True)

company_manager.py

for company in user.companies.all():
    companiesToBeIncluded.append(company.id)

Here I'm getting incorrect order of company ids. Thanks

Aarohi Kulkarni
  • 427
  • 2
  • 5
  • 19
  • I guarantee you are not getting "random records". Please show an example of the ordering in the db, what you are doing to query and display the records, and what you see. – Daniel Roseman Sep 18 '15 at 08:34
  • Yeah not actually random, but neither in the order postgres gives when I fire 'SELECT * FROM "myapp_userprofile_companies" order by id desc;' on db. See my edit. – Aarohi Kulkarni Sep 18 '15 at 08:46
  • I was wondering, why wouldn't you use `order_by('id')` in your query? – Wtower Sep 18 '15 at 08:59
  • Since it executes on the bridging table, I thought that might not work. I tried that now, still wrong order. – Aarohi Kulkarni Sep 18 '15 at 09:10

1 Answers1

0

Accessing the through table was the solution here. here's the post.

UserProfile.companies.through.objects.filter(userprofile_id = 34).order_by('id')
Community
  • 1
  • 1
Aarohi Kulkarni
  • 427
  • 2
  • 5
  • 19