`objects.get(...)` does not work as expected - django-models

I'm trying to get an object from my neo4j database using neo4django
>>> # There is a single Person object in the database, so I get a value
>>> slug=Person.objects.get().name_slug
>>> print(slug)
doe-john
>>> # ok, it's there
>>> p=Person.objects.get(name_slug=slug)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/[...]/src/neo4django/neo4django/db/models/manager.py", line 37, in get
return self.get_query_set().get(*args, **kwargs)
File "/[...]/lib/python2.7/site-packages/django/db/models/query.py", line 366, in get
% self.model._meta.object_name)
DoesNotExist: Person matching query does not exist.
>>> p=Person.objects.get(name_slug__exact=slug)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/[...]/src/neo4django/neo4django/db/models/manager.py", line 37, in get
return self.get_query_set().get(*args, **kwargs)
File "/[...]/lib/python2.7/site-packages/django/db/models/query.py", line 366, in get
% self.model._meta.object_name)
DoesNotExist: Person matching query does not exist.
The error message is not sensible. I just received the queried string from the very field, so there must be a match. Any ideas? Or did I stumble upon a bug?
This is really strange, as it works with the other properties, but not with name_slug:
>>> Person.objects.get(surname='Doe')
<Person: Person object>
>>> Person.objects.get(given_name='John')
<Person: Person object>
>>> Person.objects.get(name_slug='john-doe')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/[...]/src/neo4django/neo4django/db/models/manager.py", line 37, in get
return self.get_query_set().get(*args, **kwargs)
File "/[...]/lib/python2.7/site-packages/django/db/models/query.py", line 366, in get
% self.model._meta.object_name)
DoesNotExist: Person matching query does not exist.
>>> print( p.surname, p.given_name, p.name_slug )
(u'Doe', u'John', u'john-doe')
My model is defined as such:
class Person(models.NodeModel):
surname = models.StringProperty(required=True, indexed=True)
given_name = models.StringProperty(required=True, indexed=True)
name_slug = models.StringProperty(indexed=True)
So the only difference is that it's not required, but that should make no difference, in my understanding of the documentation.

I can't replicate this using neo4django master, on Neo4j 1.9.
I created a test_models.py
from neo4django.db import models
class Person(models.NodeModel):
class Meta:
# since test_models isn't in an app
app_label='test'
surname = models.StringProperty(required=True, indexed=True)
given_name = models.StringProperty(required=True, indexed=True)
name_slug = models.StringProperty(indexed=True)
and then ran
>>> from test_models import Person
>>> john = Person.objects.create(surname=u'Doe', given_name=u'John', name_slug=u'john-doe')
>>> Person.objects.get(name_slug='john-doe')
<Person: Person object>
>>> john == Person.objects.get(name_slug='john-doe')
True
>>> jane = Person.objects.create(surname=u'Doe', given_name=u'Jane', name_slug=u'jane-doe')
>>> jane == Person.objects.get(name_slug='jane-doe')
True
>>> jane == Person.objects.get(given_name='Jane', surname='Doe')
True
Thoughts?

Related

Field 'id' expected a number but got ' '. But I dont even have a field named 'id'

we are making a web app using Django, postgresql, and reactjs. I am creating two models and connecting them using one to one relationship in django. The view file is literally empty. This is models.py file I changed the primary key fields for each table to avoid the error but it isnot solving anything.I am new to Django. Please help.
from django.db import models
class userInfo(models.Model):
Username=models.CharField(max_length=100,primary_key=True)
Password=models.CharField(max_length=100)
def __str__(self):
return self.Username
class rentDetails(models.Model):
user=models.OneToOneField(
userInfo,
on_delete=models.CASCADE,
primary_key=True
)
floor_no=models.CharField(max_length=20,default=True)
distance=models.IntegerField(default=True)
location=models.CharField(max_length=200,default=True)
area=models.IntegerField(default=True)
no_of_rooms=models.IntegerField(default=True)
price=models.IntegerField(default=True)
property_choices=[
('hostel','Hostel'),
('house','House') ,
('room','Room'),
('flat','flat')
]
property_type=models.CharField(
max_length=10,
choices=property_choices,
)
images=models.ImageField(upload_to='uploads/',null=True)
#Here's the traceback:
Traceback (most recent call last):
File "C:\Users\acer\Documents\CHAANO\Chano\manage.py", line 22, in <module>
main()
File "C:\Users\acer\Documents\CHAANO\Chano\manage.py", line 18, in main
execute_from_command_line(sys.argv)
" ".join(
File "C:\Users\acer\Documents\python 310\lib\site-packages\django\db\backends\base\schema.py", line 296, in _iter_column_sql
default_value = self.effective_default(field)
File "C:\Users\acer\Documents\python 310\lib\site-packages\django\db\backends\base\schema.py", line 410, in effective_default
return field.get_db_prep_save(self._effective_default(field), self.connection)
File "C:\Users\acer\Documents\python 310\lib\site-packages\django\db\models\fields\related.py", line 1126, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\acer\Documents\python 310\lib\site-packages\django\db\models\fields\__init__.py", line 910, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\acer\Documents\python 310\lib\site-packages\django\db\models\fields\__init__.py", line 2668, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\acer\Documents\python 310\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got ' '.

Datastore error: BadValueError: Expected integer, got [0, 1, 2, 3]

Others have reported a similar error, but the solutions given do not solve my problem.
For example there is a good answer here. The answer in the link mentions how ndb changes from a first use to a later use and suggests there is a problem because a first run produces a None in the Datastore. I cannot reproduce or see that happening in the Datastore for my sdk, but that may be because I am running it here from the interactive console.
I am pretty sure I got an initial good run with the GAE interactive console, but every run since then has failed with the error in my Title to this question.
I have left the print statements in the following code because they show good results and assure me that the error is occuring in the put() at the very end.
from google.appengine.ext import ndb
class Account(ndb.Model):
week = ndb.IntegerProperty(repeated=True)
weeksNS = ndb.IntegerProperty(repeated=True)
weeksEW = ndb.IntegerProperty(repeated=True)
terry=Account(week=[],weeksNS=[],weeksEW=[])
terry_key=terry.put()
terry = terry_key.get()
print terry
for t in list(range(4)): #just dummy input, but like real input
terry.week.append(t)
print terry.week
region = 1 #same error message for region = 0
if region :
terry.weeksEW.append(terry.week)
else:
terry.weeksNS.append(terry.week)
print 'EW'+str(terry.weeksEW)
print 'NS'+str(terry.weeksNS)
terry.week = []
print 'week'+str(terry.week)
terry.put()
The idea of my code is to first build up the terry.week list values incrementally and then later store the whole list to the appropriate region, either NS or EW. So I'm looking for a workaround for this scheme.
The error message is likely of no value but I am reproducing it here.
Traceback (most recent call last):
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/tools/devappserver2/python/runtime/request_handler.py", line 237, in handle_interactive_request
exec(compiled_code, self._command_globals)
File "<string>", line 55, in <module>
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 3458, in _put
return self._put_async(**ctx_options).get_result()
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/tasklets.py", line 383, in get_result
self.check_success()
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/tasklets.py", line 427, in _help_tasklet_along
value = gen.throw(exc.__class__, exc, tb)
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/context.py", line 824, in put
key = yield self._put_batcher.add(entity, options)
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/tasklets.py", line 430, in _help_tasklet_along
value = gen.send(val)
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/context.py", line 358, in _put_tasklet
keys = yield self._conn.async_put(options, datastore_entities)
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/datastore/datastore_rpc.py", line 1858, in async_put
pbs = [entity_to_pb(entity) for entity in entities]
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 697, in entity_to_pb
pb = ent._to_pb()
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 3167, in _to_pb
prop._serialize(self, pb, projection=self._projection)
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1422, in _serialize
values = self._get_base_value_unwrapped_as_list(entity)
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1192, in _get_base_value_unwrapped_as_list
wrapped = self._get_base_value(entity)
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1180, in _get_base_value
return self._apply_to_values(entity, self._opt_call_to_base_type)
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1352, in _apply_to_values
value[:] = map(function, value)
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1234, in _opt_call_to_base_type
value = _BaseValue(self._call_to_base_type(value))
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1255, in _call_to_base_type
return call(value)
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1331, in call
newvalue = method(self, value)
File "/Users/brian/google-cloud-sdk/platform/google_appengine/google/appengine/ext/ndb/model.py", line 1781, in _validate
(value,))
BadValueError: Expected integer, got [0, 1, 2, 3]
I believe the error comes from these lines:
terry.weeksEW.append(terry.week)
terry.weeksNS.append(terry.week)
You are not appending another integer; You are appending a list, when an integer is expected.
>>> aaa = [1,2,3]
>>> bbb = [4,5,6]
>>> aaa.append(bbb)
>>> aaa
[1, 2, 3, [4, 5, 6]]
>>>
This fails the ndb.IntegerProperty test.
Try:
terry.weeksEW += terry.week
terry.weeksNS += terry.week
EDIT: To save a list of lists, do not use the IntegerProperty(), but instead the JsonProperty(). Better still, the ndb datastore is deprecated, so... I recommend Firestore, which uses JSON objects by default. At least use Cloud Datastore, or Cloud NDB.

How i can acces to another class, while i'm enter the information for the first class from shell?

I'm trying to fill write the models from shell and i was trying to fill the information for input has ( ForeignKey ) that make it access to another class.
that is my code in pycharm :
class Team(models.Model):
name = models.CharField(max_length=256, unique=True)
details = models.TextField()
def __str__(self):
return self.name
class Player(models.Model):
name = models.CharField(max_length=256)
number = models.IntegerField()
age = models.IntegerField()
position_in_field = models.CharField(max_length=256, choices=(('1', 'حارس'), ('2', 'دفاع'), ('3', 'وسط'), ('4', 'هجوم')))
is_captain = models.BooleanField(default=False)
team = models.ForeignKey(Team)
def __str__(self):
return '{} - {}'.format(self.name, self.team)
and this is the result:
python manage.py shell
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from teams.models import Player
>>> from teams.models import Team
>>> Player.objects.create(name='محمد إبراهيم', number='25', age='27', position_in_field='هجوم', is_captain=False, team='فريق الزمالك')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\query.py", line 392, in create
obj = self.model(**kwargs)
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\base.py", line 555, in __init__
_setattr(self, field.name, rel_obj)
File "D:\cj\projects\django\teammanager_env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 216, in __set__
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "'فريق الزمالك'": "Player.team" must be a "Team" instance.
When you create a record with a foreign key, you have to indicate the record in the referenced model through its primary key.
In the case of model Team, you didn't set a primary key explicitly, so Djangosets de default field mode_id, that is a autoincremental PositiveIntegerField, that is what you have to indicate in the referencing record.
Player.objects.create(name='محمد إبراهيم', number='25', age='27', position_in_field='هجوم', is_captain=False, team_id=1)
If you have a model object with the referenced team, you can use it too:
Player.objects.create(name='محمد إبراهيم', number='25', age='27', position_in_field='هجوم', is_captain=False, team=team_instance)

Cannot Query Array of Integers in Postgres

Migrated column type from HSTORE to JSONB and am using this snippet of code...
from sqlalchemy.dialects.postgresql import ARRAY, JSONB
if employment_type:
base = base.filter(Candidate.bio["employment_type"].cast(ARRAY).contains(employment_type))
and am getting this error...
127.0.0.1 - - [28/Mar/2016 12:25:13] "GET /candidate_filter/?employment_type_3=true HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/surajkapoor/Desktop/lhv-talenttracker/app/views.py", line 660, in investor_filter
base = base.filter(Candidate.bio["employment_type"].cast(ARRAY).contains(employment_type))
File "/Library/Python/2.7/site-packages/sqlalchemy/dialects/postgresql/json.py", line 93, in cast
return self.astext.cast(type_)
File "/Library/Python/2.7/site-packages/sqlalchemy/dialects/postgresql/json.py", line 95, in cast
return sql.cast(self, type_)
File "<string>", line 2, in cast
File "/Library/Python/2.7/site-packages/sqlalchemy/sql/elements.py", line 2314, in __init__
self.type = type_api.to_instance(type_)
File "/Library/Python/2.7/site-packages/sqlalchemy/sql/type_api.py", line 1142, in to_instance
return typeobj(*arg, **kw)
TypeError: __init__() takes at least 2 arguments (1 given)
Candidate.bio["employment_type"] is an array of integers and I'm simply trying to query all the rows that contain a specific integer in them.
Also, .cast() works perfectly on the same column when calling Integer...
if internship:
base = base.filter(Candidate.bio["internship"].cast(Integer) == 1)
SqlAlchemy is probably having difficulty constructing the where clause because it can't figure out what type bio->'employment_type' is.
If the contains method is called from a String object, it would generate a LIKE clause, but for JSONB or ARRAY it would need to generate the #> operator.
To give SqlAlchemy the necessary hints, use explicit casting everywhere, i.e. write your query like
from sqlalchemy import cast
if employment_type:
casted_field = Candidate.bio['employment_type'].cast(JSONB)
casted_values = cast(employment_type, JSONB)
stmt = base.filter(casted_field.contains(casted_values))
In my example, I have a JSONB column named bio with the following data:
{"employment_type": [1, 2, 3]}
Edit: Casting to JSONB works:
>>> from sqlalchemy.dialects.postgresql import JSONB
>>> employment_type = 2
>>> query = (
... session.query(Candidate)
... .filter(Candidate.bio['employment_type'].cast(JSONB).contains(employment_type)))
>>> query.one().bio
{"employment_type": [1, 2, 3]}
Original answer:
I couldn't get .contains to work on Candidate.bio['employment_type'], but we can do the equivalent of the following SQL:
SELECT * FROM candidate WHERE candidate.bio #> '{"employment_type": [2]}';
like this:
>>> employment_type = 2
>>> test = {'employment_type': [employment_type]}
>>> query = (
... session.query(Candidate)
... .filter(Candidate.bio.contains(test)))
>>> query.one().bio
{"employment_type": [1, 2, 3]}

Unknown field(s) (...) specified for MyModel

I have been searching through solutions to this error, but for everyone else it seems to be caused by a slightly different reason. I have a models.py that looks something like the following:
class MyModel(models.Model):
something1 = models.IntegerField()
something2 = models.CharField(max_length=256)
something3 = models.CharField(max_length=256)
class MyModelForm(ModelForm):
class Meta:
model = MyModel
fields = ('something1', 'something2',)
Say I don't actually want to use 'something3' anymore. If I delete it, and even delete and re-sync the database, I get an error saying
Unknown field(s) (something3) specified for MyModel.
This happens, as far as I have noticed, when I save anything using
saveThis = MyModel(something1=x, something2=y)
saveThis.save()
Any ideas what is throwing this error? I have even done a search through all documents to make sure 'something3' is not in any of them. Here is the traceback:
File "/Users/me/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/core/handlers/base.py", line 92, in get_response
response = middleware_method(request)
File "/Users/me/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/middleware/common.py", line 69, in process_request
if (not urlresolvers.is_valid_path(request.path_info, urlconf) and
File "/Users/me/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/core/urlresolvers.py", line 551, in is_valid_path
resolve(path, urlconf)
File "/Users/me/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/core/urlresolvers.py", line 440, in resolve
return get_resolver(urlconf).resolve(path)
File "/Users/me/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/core/urlresolvers.py", line 319, in resolve
for pattern in self.url_patterns:
File "/Users/me/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/core/urlresolvers.py", line 347, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Users/me/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/core/urlresolvers.py", line 342, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/Users/me/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/me/Sites/myproj/myproj/urls.py", line 2, in <module>
from myproj.views import myView1, myview2,...
File "/Users/me/Sites/myproj/myproj/views.py", line 4, in <module>
from mainapp.models import MyModel
File "/Users/me/Sites/myproj/myproj/mainapp/models.py", line 80, in <module>
class MyModelForm(ModelForm):
File "/Users/me/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/django/forms/models.py", line 221, in __new__
raise FieldError(message)
FieldError: Unknown field(s) (something3) specified for MyModel

Resources