0

in my previous question how-to-save-many-to-many-relationship-in-django helped me about how to save many to many but i have some issue to save. Here we go..

I have the forloop template like

{% for items in store %}
<input type="checkbox" value="{{ items.id|safe }}" name="store[]">
{% endfor %

And the mission here is i am going to save many to many relation.

so

if request.method == 'POST':
    ...
    new_track.save()
    some_var = request.POST.getlist('store[]')

some_var giving me this [u'2', u'4', u'3']

    new_store = Store.objects.filter(id__in=some_var)
    pprint.pprint(new_store)
    new_track.store.add(new_store)

new_store giving me this [<Store: Store object>, <Store: Store object>, <Store: Store object>]. Previously i tried with objects.get() that was working but saving multiple i come to use filter but don't know how to save multiple object. Now i have the error is

int() argument must be a string or a number, not 'QuerySet'

Updated:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/dashboard/track_info/10/

Django Version: 1.7
Python Version: 2.7.6
Installed Applications:
('django.contrib.sites',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'dsp',
 'frontend',
 'ckeditor',
 'social.apps.django_app.default')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


    Traceback:
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
      22.                 return view_func(request, *args, **kwargs)
    File "/home/ri/studio/Audiotube/dsp/decorators.py" in inner
      46.           return view(request, *args, **kwargs)
    File "/home/ri/studio/Audiotube/dsp/views.py" in track_infodetail
      338.         new_track.store.add(new_store)
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in add
      917.             self._add_items(self.source_field_name, self.target_field_name, *objs)
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in _add_items
      1010.                     '%s__in' % target_field_name: new_ids,
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/query.py" in filter
      691.         return self._filter_or_exclude(False, *args, **kwargs)
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
      709.             clone.query.add_q(Q(*args, **kwargs))
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
      1287.         clause, require_inner = self._add_q(where_part, self.used_aliases)
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
      1314.                     current_negated=current_negated, connector=connector)
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
      1181.                                                     lookups, value)
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/fields/related.py" in get_lookup_constraint
      1550.             root_constraint.add(lookup_class(Col(alias, targets[0], sources[0]), value), AND)
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/lookups.py" in __init__
      82.         self.rhs = self.get_prep_lookup()
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/lookups.py" in get_prep_lookup
      85.         return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs)
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_lookup
      648.             return [self.get_prep_value(v) for v in value]
    File "/home/ri/studio/env/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
      915.         return int(value)

    Exception Type: TypeError at /dashboard/track_info/10/
    Exception Value: int() argument must be a string or a number, not 'QuerySet'
Community
  • 1
  • 1

2 Answers2

2

add takes multiple objects as arguments. This should work

new_track.store.add(*new_store)

Django Documentation on Many-to-Many

sagarchalise
  • 992
  • 8
  • 14
1

new_store is a queryset, not a single object. Using the get() method will only return a single model object.

Instead, you must interact with each object in the queryset if you wish to use the same process that was working for get(). As such, you can use for each_store in new_store: new_track.store.add(each_store)

(Edited to get rid of conjecture; the above will work but there should be more performance-friendly ways to do this if that is a concern)

I suspect that the error is related to Django attempting to pass the pk of a single object for the add function, preparing the value as an integer before doing some database operation. Expecting an integer to find the field but instead getting passed the queryset object type spits out the error you see.

Ian Price
  • 7,416
  • 2
  • 23
  • 34
  • so i guess bulk_create is good option, Can you give sample how to do that in my case.? –  Sep 29 '14 at 06:55
  • Actually, a simpler approach... Adding the _set using this code... (Untested, but have used a similar approach a ways back) `new_track.store_set.add(new_store)` – Ian Price Sep 29 '14 at 06:58
  • _set throws `'Tracks' object has no attribute 'store_set'` –  Sep 29 '14 at 07:06
  • bulk_create won't work with many to many relation, _set is for reverse relation lookup on foreignkeys AFAIK. https://docs.djangoproject.com/en/dev/ref/models/querysets/#bulk-create – sagarchalise Sep 29 '14 at 07:09
  • @IanPrice using AFAIK i am not getting any error, but workbench shows me only one object entry... – Raja Simon Sep 29 '14 at 07:17