0

I'm working on a small project using Django / Rest Framework I would like to know if there is any way to pass a list like that

mycontact = Contact.objects.get(id=[14,26,44,88])

instead of

mycontact = Contact.objects.get(id=14)

This is my full code :

@action(methods=['post'], detail=False)
def listin(self, request):
    mylist = List.objects.get(id=request.data['listId'])
    mycontact = Contact.objects.filter(id__in=[14,26,44,88])
    mycontact.list.add(mylist)
    return Response("Good")

i'm looking for a solution because I have manyTomanyField

4 Answers4

1

get accepts only one argument If you want to pass a list of ids you can do this

mycontact = Contact.objects.filter(id__in=[14,26,44,88])  # this will return an iterable queryset
or
mycontact = list(Contact.objects.filter(id__in=[14,26,44,88]))  # this will return a list
ramwin
  • 5,803
  • 3
  • 27
  • 29
Jay Prakash
  • 149
  • 10
0

Jay's answer is likely what you are looking for. But, in case you need an alternative

contacts = [Contact.objects.get(id=id) for id in (14, 26, 44, 88)]
zerecees
  • 697
  • 4
  • 13
0

You can use get() for getting single unique object, for getting multiple id objects you can use filter().

Try using below statement

mycontact = Contact.objects.filter(id__in=[14,26,44,88])

When you want to use list of parameters to find, can use in operator.

0

Also, if your database table has too many records, consider using in_bulk.

mycontact = Contact.objects.in_bulk([14,26,44,88])

UPD:

In your case, loop through the mycontact queryset and set the mylist to each object:

mylist = List.objects.get(id=request.data['listId'])
mycontact = Contact.objects.filter(id__in=[14,26,44,88])
for contact in mycontact:
    contact.list.add(mylist)

or simply do it vice-versa:

mylist = List.objects.get(id=request.data['listId'])
mylist.contact_set.set([14,26,44,88])

Note: I used default related name contact_set

Ersain
  • 1,466
  • 1
  • 9
  • 20