Skip to content

Commit 3c80b9d

Browse files
committed
Cast type using the type of the field being referenced.
Usually this is just the pk type (int or string), but if this is an inherited model then it has a rel using a OneToOneField pointing to the base model. Fixes: #153 Solution from here: #203 (original fork from @adsva is deleted so I cannot test and merge that)
1 parent a1279fa commit 3c80b9d

File tree

2 files changed

+30
-11
lines changed

2 files changed

+30
-11
lines changed

ajax_select/lookup_channel.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -86,23 +86,21 @@ def format_item_display(self, obj):
8686
return escape(force_text(obj))
8787

8888
def get_objects(self, ids):
89-
"""This is used to retrieve the currently selected objects for either ManyToMany or ForeignKey.
90-
91-
Note that the order of the ids supplied for ManyToMany fields is dependent on how the
92-
objects manager fetches it.
93-
ie. what is returned by `YourModel.{fieldname}_set.all()`
94-
95-
In most situations (especially postgres) this order is indeterminate -- not the order that you originally
96-
added them in the interface.
97-
See :doc:`/Ordered-ManyToMany` for a solution to this.
89+
"""
90+
This is used to retrieve the currently selected objects for either ManyToMany or ForeignKey.
9891
9992
Args:
10093
ids (list): list of primary keys
10194
Returns:
10295
list: list of Model objects
10396
"""
104-
# return objects in the same order as passed in here
105-
pk_type = self.model._meta.pk.to_python
97+
if self.model._meta.pk.rel is not None:
98+
# Use the type of the field being referenced
99+
pk_type = self.model._meta.pk.target_field.to_python
100+
else:
101+
pk_type = self.model._meta.pk.to_python
102+
103+
# Return objects in the same order as passed in here
106104
ids = [pk_type(pk) for pk in ids]
107105
things = self.model.objects.in_bulk(ids)
108106
return [things[aid] for aid in ids if aid in things]

tests/test_lookups.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
2+
from django.test import TestCase
3+
from django.contrib.auth.models import User
4+
from .lookups import UserLookup
5+
6+
7+
class TestLookups(TestCase):
8+
9+
def test_get_objects(self):
10+
user1 = User.objects.create(username='user1',
11+
12+
password='password')
13+
user2 = User.objects.create(username='user2',
14+
15+
password='password')
16+
lookup = UserLookup()
17+
users = lookup.get_objects([user2.id, user1.id])
18+
self.assertEqual(len(users), 2)
19+
u2, u1 = users
20+
self.assertEqual(u1, user1)
21+
self.assertEqual(u2, user2)

0 commit comments

Comments
 (0)