"failed to locate a name" error when using model with relationship

8,945 views
Skip to first unread message

trust...@gmail.com

unread,
Jul 1, 2014, 1:17:55 PM7/1/14
to sqlal...@googlegroups.com
I have two classes, Artwork and Person. Artwork has a relationship to Person.
However, when I try to use them, I get an error thrown:
InvalidRequestError: When initializing mapper Mapper|Artwork|artwork, expression 'Person' failed to locate a name ("name 'Person' is not defined"). If this is a class name, consider adding this relationship() to the <class 'model.Artwork'> class after both dependent classes have been defined.


Here are the classes themselves, defined in model/__init__.py
class Artwork(db.Model, SimpleSerializeMixin):
    id = db.Column(db.Integer, primary_key=True)
    ....
    artist_id = db.Column(db.String(256), db.ForeignKey('person.sub'))
    artist = db.relationship('Person', backref='artworks')

class Person(db.Model, SimpleSerializeMixin):
    sub = db.Column(db.String(256), primary_key=True)


I checked with debugger and in sqlalchemy/ext/declarative/clsregistry.py (_class_resolver.__call__())
there is a line:
x = eval(self.arg, globals(), self._dict)
No "Person" or "Artwork" or any other class defined in the file are present in globals(). self._dict is empty
So it fails with an NameError exception.

What could be the issue ?

Mike Bayer

unread,
Jul 1, 2014, 2:05:11 PM7/1/14
to sqlal...@googlegroups.com
it's usually that the Person code wasn't run, e.g. that the module in which it is located was not imported, before you tried to use the Artwork class.  All the tables/classes can be introduced to the Python interpreter in any order, but once you try to "use" the mapping, e.g. make an object or run a query, it resolves all the links and everything has to be present.




--
You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.
To post to this group, send email to sqlal...@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

trust...@gmail.com

unread,
Jul 2, 2014, 10:21:33 AM7/2/14
to sqlal...@googlegroups.com
Hi Michael, thank you for the answer.
Both classes are in the same file so I don't see how it could be possible that one class is used while other is not imported.
Could you help me with that ?

Andrey

вторник, 1 июля 2014 г., 21:05:11 UTC+3 пользователь Michael Bayer написал:

Mike Bayer

unread,
Jul 2, 2014, 10:38:55 AM7/2/14
to sqlal...@googlegroups.com

On 7/2/14, 10:21 AM, trust...@gmail.com wrote:
Hi Michael, thank you for the answer.
Both classes are in the same file so I don't see how it could be possible that one class is used while other is not imported.
Could you help me with that ?

that would mean you're doing something that is invoking Artwork as a mapped class and causing the mapper config step to occur before it gets down to Person.   The stack trace here would show exactly where that originates.

trust...@gmail.com

unread,
Jul 3, 2014, 3:23:31 AM7/3/14
to sqlal...@googlegroups.com
Hi, Michael,

here is the stack trace:
  File "/home/andrey/projects/art/artFlask/api/artList.py", line 30, in post
    item = app_ctx.create_item_from_context()
  File "/home/andrey/projects/art/artFlask/utils/app_ctx.py", line 53, in create_item_from_context
    item = ModelClass(**data)
  File "<string>", line 2, in __init__
    
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 322, in _new_state_if_none
    state = self._state_constructor(instance, self)
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 712, in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 155, in _state_constructor
    self.dispatch.first_init(self, self.class_)
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/event/attr.py", line 257, in __call__
    fn(*args, **kw)
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 2673, in _event_on_first_init
    configure_mappers()
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 2569, in configure_mappers
    mapper._post_configure_properties()
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 1682, in _post_configure_properties
    prop.init()
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/orm/interfaces.py", line 143, in init
    self.do_init()
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1510, in do_init
    self._process_dependent_arguments()
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1567, in _process_dependent_arguments
    self.target = self.mapper.mapped_table
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 712, in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1484, in mapper
    argument = self.argument()
  File "/home/andrey/envs/art_flask2/lib/python2.7/site-packages/sqlalchemy/ext/declarative/clsregistry.py", line 275, in __call__
    (self.prop.parent, self.arg, n.args[0], self.cls)
InvalidRequestError: When initializing mapper Mapper|Artwork|artwork, expression 'Person' failed to locate a name ("name 'Person' is not defined"). If this is a class name, consider adding this relationship() to the <class 'model.Artwork'> class after both dependent classes have been defined.

Does it tell you anything ?

среда, 2 июля 2014 г., 17:38:55 UTC+3 пользователь Michael Bayer написал:

Mike Bayer

unread,
Jul 3, 2014, 10:33:09 AM7/3/14
to sqlal...@googlegroups.com

On 7/3/14, 3:23 AM, trust...@gmail.com wrote:
> Hi, Michael,
>
> here is the stack trace:
> File "/home/andrey/projects/art/artFlask/api/artList.py", line 30,
> in post
> item = app_ctx.create_item_from_context()
> File "/home/andrey/projects/art/artFlask/utils/app_ctx.py", line 53,
> in create_item_from_context
> item = ModelClass(**data)
> File "<string>", line 2, in __init__

this means on line 30 of your artList.py class, the "Person" class
hasn't been set up yet, or was set up and failed to do so and for some
reason the error didn't get reported (such as if some unusual system of
loading modules were present).


trust...@gmail.com

unread,
Jul 3, 2014, 11:45:41 AM7/3/14
to sqlal...@googlegroups.com
Adding import instruction to artList.py didn't seem to help:
from model import Artwork, Person

What else can I do ?

четверг, 3 июля 2014 г., 17:33:09 UTC+3 пользователь Michael Bayer написал:

trust...@gmail.com

unread,
Jul 3, 2014, 1:19:15 PM7/3/14
to sqlal...@googlegroups.com
Mike, here is the source for the models:

I would really apprieciate your feedback on this, I'm really new to flask and SQLAlchemy.
The other source files (artList.py etc) are also there.

Thank you,
Andrey

четверг, 3 июля 2014 г., 17:33:09 UTC+3 пользователь Michael Bayer написал:

Mike Bayer

unread,
Jul 3, 2014, 1:39:41 PM7/3/14
to sqlal...@googlegroups.com
this project needs:

1. a package

2. a setup.py file

3. a requirements.txt file


I am running in each dependency indivdually as I get import errors.  very painful.

Mike Bayer

unread,
Jul 3, 2014, 1:41:55 PM7/3/14
to sqlal...@googlegroups.com
to start with, you have an import cycle. fix that first.

classics-MacBook-Pro-2:artFlask classic$ .venv/bin/python
Python 2.7.5 (default, Mar  7 2014, 19:17:16)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import model
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "model/__init__.py", line 1, in <module>
    from app import db
  File "app/__init__.py", line 46, in <module>
    import views
  File "/Users/classic/Desktop/tmp/artFlask/views.py", line 4, in <module>
    from api.artists import Artists
  File "/Users/classic/Desktop/tmp/artFlask/api/artists.py", line 32, in <module>
    from utils.app_ctx import ApplicationContext
  File "/Users/classic/Desktop/tmp/artFlask/utils/app_ctx.py", line 1, in <module>
    from model import Artwork
ImportError: cannot import name Artwork


well fix the package part first.  then fix the import cycle.

trust...@gmail.com

unread,
Jul 3, 2014, 3:29:34 PM7/3/14
to sqlal...@googlegroups.com
Hi Mike!

I've updated requirements. Let me check if I didn't commit something.

четверг, 3 июля 2014 г., 20:41:55 UTC+3 пользователь Michael Bayer написал:

Mike Bayer

unread,
Jul 3, 2014, 3:43:45 PM7/3/14
to sqlal...@googlegroups.com
OK thats great but you have a long way to go:

import cycle:


classic$ .venv/bin/python
Python 2.7.5 (default, Mar  7 2014, 19:17:16)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import model
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "model/__init__.py", line 1, in <module>
    from app import db
  File "app/__init__.py", line 46, in <module>
    import views
  File "/Users/classic/Desktop/tmp/artFlask/views.py", line 4, in <module>
    from api.artists import Artists
  File "/Users/classic/Desktop/tmp/artFlask/api/artists.py", line 32, in <module>
    from utils.app_ctx import ApplicationContext
  File "/Users/classic/Desktop/tmp/artFlask/utils/app_ctx.py", line 1, in <module>
    from model import Artwork
ImportError: cannot import name Artwork
>>>



tests dont run:

$ .venv/bin/nosetests -v
Failure: ImportError (No module named mail) ... ERROR
Failure: ImportError (No module named app) ... ERROR
Failure: ImportError (No module named app) ... ERROR

======================================================================
ERROR: Failure: ImportError (No module named mail)
----------------------------------------------------------------------

Traceback (most recent call last):
  File "/Users/classic/Desktop/tmp/artFlask/.venv/lib/python2.7/site-packages/nose/loader.py", line 414, in loadTestsFromName
    addr.filename, addr.module)
  File "/Users/classic/Desktop/tmp/artFlask/.venv/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/Users/classic/Desktop/tmp/artFlask/.venv/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/Users/classic/Desktop/tmp/artFlask/app/__init__.py", line 6, in <module>
    from mail import mail
ImportError: No module named mail

etc.

These are all very basic Python issues.  If you can get on IRC and get someone to help you get your program just to import in a basic way you can probably figure out why your models aren't initializing.    Good luck!

trust...@gmail.com

unread,
Jul 3, 2014, 5:20:17 PM7/3/14
to sqlal...@googlegroups.com
Muchos grasias, Michael!

Issue resolved.
There were a couple of other ForeignKey issues, seems to be okay now.
So far I understand that there is a lot to learn for me, so I was wondering - do you by chance accept apprentices ?

I would be willing to help writing fixes/minor features whatever for an exchange of your guidance. What do you say?

No matter what, thank you again for assistance in these issues. I'm now going to test and fix everything else :-)

Andrey

Mike Bayer

unread,
Jul 5, 2014, 11:14:42 AM7/5/14
to sqlal...@googlegroups.com
I've figured out a way to mark mostly small issues as "sprintable":
https://bitbucket.org/zzzeek/sqlalchemy/issues?status=new&status=open&sort=-priority&responsible=sqlalchemy_sprinters

most of the work with these is in writing a simple test and a properly
formatted changelog message (I'm tired of always writing those
myself). It's a lot of "wax on/wax off" stuff (if you dont get the
reference: http://www.youtube.com/watch?v=fULNUr0rvEc)


Reply all
Reply to author
Forward
0 new messages