#13155: Iteration of a Many To Many Relationship raises Field Error
---------------------------------------------------+------------------------
Reporter: callen | Owner: nobody
Status: reopened | Milestone:
Component: Database layer (models, ORM) | Version: 1.1
Resolution: | Keywords: m2m, orm,
field error
Stage: Unreviewed | Has_patch: 0
Needs_docs: 0 | Needs_tests: 0
Needs_better_patch: 0 |
---------------------------------------------------+------------------------
Comment (by callen):
I've found a reliable way to reproduce it, via the "shell_plus" manage.py
command provided by django-command-extensions.
I've included the shell session that reproduced the error as well as
including the source to the shell_plus command.
This gives me a couple guesses as to what is going on, but I'm not 100%
certain.
{{{
patras:socceramerica callen$ python ./manage.py shell_plus
From 'sites' autoload: Site
From 'auth' autoload: Permission, Group, User, Message
From 'contenttypes' autoload: ContentType
From 'sessions' autoload: Session
From 'admin' autoload: LogEntry
From 'comments' autoload: Comment, CommentFlag
From 'flatpages' autoload: FlatPage
From 'redirects' autoload: Redirect
From 'venus' autoload: MenuType, SubType, Category, Author, Type, Tag,
Article, ArticleMeta, Change, ArticleOffsite, TypeFormField, InlineImage,
Note, SphinxCounter
From 'mailer' autoload: Message, DontSendEntry, MessageLog
From 'base' autoload: Category, Type, Region, Tournament
From 'account' autoload: State, Country, Source, Involvement,
InvolvementLevel, TransactionType, PaymentType, CreditCardType,
UpdateType, Effort, MembershipType, Address, UserExtra, CreditCard,
Transaction, Update, Notification, Decline, Issue, IssuePurchases
From 'merx' autoload: Construct, Newsletter, NewsletterArticle,
MasterList, Subscription, Edition, EditionContent, ApiEdition, ApiCall,
ApiLog, BadEmail
From 'migration' autoload: SaTournament, AuthorMap, OldState, OldCountry,
CommentAuthorMap, SubscriptionHash, Image, ArticleTags, ArticleType,
Articles, ArticlesAdmin, ArticlesDigest, ArticlesImages, ArticlesMagazine,
Authors, AuthorsBlog, AwardsYsa, Dborderitems, Dborderpayments, Cctemp,
MigrationCc, CompRenewals, Members, MembersHistory, MembersLogChanges,
MembersLogVisits, MembersRemoved, MembersSubEmail, MembersSubMagazine,
Pemailexpiration, Pmemberships, WorldCupWatchComments,
MlsConfidentialComments, YouthSoccerInsiderComments,
SoccerBusinessInsiderComments, GrassrootsSoccerBizComments,
SoccerTalkComments, PaypalUser
Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12)
Type "copyright", "credits" or "license" for more information.
IPython 0.9.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: Newsletter.objects.get(id = 2)
---------------------------------------------------------------------------
DoesNotExist Traceback (most recent call
last)
/Users/callen/code/socceramerica/<ipython console> in <module>()
/Library/Python/2.5/site-packages/django/db/models/manager.pyc in
get(self, *args, **kwargs)
118
119 def get(self, *args, **kwargs):
--> 120 return self.get_query_set().get(*args, **kwargs)
121
122 def get_or_create(self, **kwargs):
/Library/Python/2.5/site-packages/django/db/models/query.pyc in get(self,
*args, **kwargs)
303 if not num:
304 raise self.model.DoesNotExist("%s matching query does
not exist."
--> 305 % self.model._meta.object_name)
306 raise self.model.MultipleObjectsReturned("get() returned
more than one %s -- it returned %s! Lookup parameters were %s"
307 % (self.model._meta.object_name, num, kwargs))
DoesNotExist: Newsletter matching query does not exist.
In [2]: Newsletter.objects.get(id = 10)
---------------------------------------------------------------------------
DoesNotExist Traceback (most recent call
last)
/Users/callen/code/socceramerica/<ipython console> in <module>()
/Library/Python/2.5/site-packages/django/db/models/manager.pyc in
get(self, *args, **kwargs)
118
119 def get(self, *args, **kwargs):
--> 120 return self.get_query_set().get(*args, **kwargs)
121
122 def get_or_create(self, **kwargs):
/Library/Python/2.5/site-packages/django/db/models/query.pyc in get(self,
*args, **kwargs)
303 if not num:
304 raise self.model.DoesNotExist("%s matching query does
not exist."
--> 305 % self.model._meta.object_name)
306 raise self.model.MultipleObjectsReturned("get() returned
more than one %s -- it returned %s! Lookup parameters were %s"
307 % (self.model._meta.object_name, num, kwargs))
DoesNotExist: Newsletter matching query does not exist.
In [3]: Newsletter.objects.get(id = 80)
Out[3]: <Newsletter: Soccer on TV>
In [4]: Bimport
---------------------------------------------------------------------------
NameError Traceback (most recent call
last)
/Users/callen/code/socceramerica/<ipython console> in <module>()
NameError: name 'Bimport' is not defined
In [5]: from bimport.models import *
In [6]: Bimport
Out[6]: <class 'bimport.models.Bimport'>
In [7]: pinfo Bimport
Type: ModelBase
Base Class: <class 'django.db.models.base.ModelBase'>
String Form: <class 'bimport.models.Bimport'>
Namespace: Interactive
File: /Users/callen/code/socceramerica/bimport/models.py
Docstring:
Bimport(id, content_type_id, source_id, import_date, datafile, error,
status)
Constructor information:
Definition: Bimport(self, *args, **kwargs)
In [8]: Bimport.objects.get(id = 20)
Out[8]: <Bimport: Bimport object>
In [9]: Bimport.objects.get(id = 20).status
Out[9]: u'P'
In [10]: Bimport.objects.get(id = 20).newsletters
Out[10]: <django.db.models.fields.related.ManyRelatedManager object at
0x16ae8d0>
In [11]: Bimport.objects.get(id = 20).newsletters.all()
---------------------------------------------------------------------------
FieldError Traceback (most recent call
last)
/Users/callen/code/socceramerica/<ipython console> in <module>()
/Library/Python/2.5/site-packages/django/db/models/manager.pyc in
all(self)
103
104 def all(self):
--> 105 return self.get_query_set()
106
107 def count(self):
/Library/Python/2.5/site-packages/django/db/models/fields/related.pyc in
get_query_set(self)
422
423 def get_query_set(self):
--> 424 return
superclass.get_query_set(self)._next_is_sticky().filter(**(self.core_filters))
425
426 # If the ManyToMany relation has an intermediary model,
/Library/Python/2.5/site-packages/django/db/models/query.pyc in
filter(self, *args, **kwargs)
496 set.
497 """
--> 498 return self._filter_or_exclude(False, *args, **kwargs)
499
500 def exclude(self, *args, **kwargs):
/Library/Python/2.5/site-packages/django/db/models/query.pyc in
_filter_or_exclude(self, negate, *args, **kwargs)
514 clone.query.add_q(~Q(*args, **kwargs))
515 else:
--> 516 clone.query.add_q(Q(*args, **kwargs))
517 return clone
518
/Library/Python/2.5/site-packages/django/db/models/sql/query.pyc in
add_q(self, q_object, used_aliases)
1673 else:
1674 self.add_filter(child, connector,
q_object.negated,
-> 1675 can_reuse=used_aliases)
1676 if connector == OR:
1677 # Aliases that were newly added or not used at
all need to
/Library/Python/2.5/site-packages/django/db/models/sql/query.pyc in
add_filter(self, filter_expr, connector, negate, trim, can_reuse,
process_extras)
1567 field, target, opts, join_list, last, extra_filters =
self.setup_joins(
1568 parts, opts, alias, True, allow_many,
can_reuse=can_reuse,
-> 1569 negate=negate, process_extras=process_extras)
1570 except MultiJoin, e:
1571 self.split_exclude(filter_expr,
LOOKUP_SEP.join(parts[:e.level]),
/Library/Python/2.5/site-packages/django/db/models/sql/query.pyc in
setup_joins(self, names, opts, alias, dupe_multis, allow_many,
allow_explicit_fk, can_reuse, negate, process_extras)
1735 names = opts.get_all_field_names() +
self.aggregate_select.keys()
1736 raise FieldError("Cannot resolve keyword %r
into field. "
-> 1737 "Choices are: %s" % (name, ",
".join(names)))
1738
1739 if not allow_many and (m2m or not direct):
FieldError: Cannot resolve keyword 'bimport' into field. Choices are:
archive_column, archive_order, article, construct, day, edition,
frequency, frequency_text, from_email, html_template, id, is_public,
list_name, name, newsletterarticle, newsletterarticles, slug, subject,
subject_type, subscription, text_template, time
}}}
shell_plus from django-command-extensions
{{{import os
from django.core.management.base import NoArgsCommand
from optparse import make_option
class Command(NoArgsCommand):
option_list = NoArgsCommand.option_list + (
make_option('--plain', action='store_true', dest='plain',
help='Tells Django to use plain Python, not IPython.'),
make_option('--no-pythonrc', action='store_true',
dest='no_pythonrc',
help='Tells Django to use plain Python, not IPython.'),
)
help = "Like the 'shell' command but autoloads the models of all
installed Django apps."
requires_model_validation = True
def handle_noargs(self, **options):
# XXX: (Temporary) workaround for ticket #1796: force early
loading of all
# models from installed apps. (this is fixed by now, but leaving
it here
# for people using 0.96 or older trunk (pre [5919]) versions.
from django.db.models.loading import get_models, get_apps
loaded_models = get_models()
use_plain = options.get('plain', False)
use_pythonrc = not options.get('no_pythonrc', True)
# Set up a dictionary to serve as the environment for the shell,
so
# that tab completion works on objects that are imported at
runtime.
# See ticket 5082.
from django.conf import settings
imported_objects = {'settings': settings}
for app_mod in get_apps():
app_models = get_models(app_mod)
if not app_models:
continue
model_labels = ", ".join([model.__name__ for model in
app_models])
print self.style.SQL_COLTYPE("From '%s' autoload: %s" %
(app_mod.__name__.split('.')[-2], model_labels))
for model in app_models:
try:
imported_objects[model.__name__] =
getattr(__import__(app_mod.__name__, {}, {}, model.__name__),
model.__name__)
except AttributeError, e:
print self.style.ERROR_OUTPUT("Failed to import '%s'
from '%s' reason: %s" % (model.__name__, app_mod.__name__.split('.')[-2],
str(e)))
continue
try:
if use_plain:
# Don't bother loading IPython, because the user wants
plain Python.
raise ImportError
import IPython
# Explicitly pass an empty list as arguments, because
otherwise IPython
# would use sys.argv from this script.
shell = IPython.Shell.IPShell(argv=[],
user_ns=imported_objects)
shell.mainloop()
except ImportError:
# Using normal Python shell
import code
try: # Try activating rlcompleter, because it's handy.
import readline
except ImportError:
pass
else:
# We don't have to wrap the following import in a 'try',
because
# we already know 'readline' was imported successfully.
import rlcompleter
readline.set_completer(rlcompleter.Completer(imported_objects).complete)
readline.parse_and_bind("tab:complete")
# We want to honor both $PYTHONSTARTUP and .pythonrc.py, so
follow system
# conventions and get $PYTHONSTARTUP first then import user.
if use_pythonrc:
pythonrc = os.environ.get("PYTHONSTARTUP")
if pythonrc and os.path.isfile(pythonrc):
try:
execfile(pythonrc)
except NameError:
pass
# This will import .pythonrc.py as a side-effect
import user
code.interact(local=imported_objects)
}}}
--
Ticket URL: <http://code.djangoproject.com/ticket/13155#comment:8>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-updates?hl=en.