mongoengine save method is deprecated? - python

I wonder why my python says that mongoengine save() method is deprecated? I don't see any info about this into official documentation https://mongoengine.readthedocs.io/en/v0.9.0/apireference.html
class MyModel(Document):
user_id = StringField(required=True)
date = DateTimeField(required=True, default=datetime.datetime.now)
my = MyModel()
my.user_id = 'user'
my.save()
and now i see:
/Library/Python/2.7/site-packages/mongoengine/document.py:340:
DeprecationWarning: save is deprecated. Use insert_one or replace_one
instead
I've python 2.7 and also installed pymongo, mongoengine and bottle-mongo (maybe some issues with that?)

MongoEngine wraps PyMongo, which deprecated "save" in PyMongo 3.0:
http://api.mongodb.com/python/current/changelog.html#collection-changes
MongoEngine might need to deprecate its save method, or suppress the deprecation warning, or perhaps some other fix to handle this PyMongo change. I recommend you search MongoEngine's bug tracker and report this issue if it has not been already.
MongoEngine Bug - https://github.com/MongoEngine/mongoengine/issues/1491

Using col.replace_one({‘_id': doc['_id']}, doc, True) instead.
The api is replace_one(filter, replacement, upsert=False, bypass_document_validation=False, collation=None, session=None).
Using upsert = True to insert a new doc if the filter find nothing.

Related

Marshmallow Field not loading default value

I have a Marshmallow Schema defined as:
class MySchema:
myfield = fields.Str(required=False, default=“value”)
When I do:
s = MySchema().load({})
I would expect the return to be:
{‘myfield’:’value’}
But I am getting {} in return.
Is there anything am I missing?
Edit:
I’m using marshmallow 3.11 due to project limitations.
I can’t upgrade to 3.15. Tried with 3.15 and it is working as expected.
Until marshmallow 3.12:
default: value to use by default when dumping (serializing)
missing: value to use by default when loading (deserializing)
Since marshmallow 3.13:
dump_default: value to use by default when dumping (serializing)
load_default: value to use by default when loading (deserializing)
default / missing still behave the same in marshmallow 3.13+ but issue a deprecation warning.
https://marshmallow.readthedocs.io/en/stable/changelog.html#id4

Is get_validation_exclusions method of ModelSerializer in Django Rest Framework removed in latest versions?

While running the below code:
class PostSerializer(serializers.ModelSerializer):
author = UserSerializer(required=False)
def get_validation_exclusions(self):
exclusions = super(PostSerializer, self).get_validation_exclusions()
return exclusions + ['author']
I am getting the error Column 'author' cannot be null. When I checked online for documentation, this method is not available since 3.0 release (link: http://www.cdrf.co/3.3/rest_framework.serializers/ModelSerializer.html). Please let me know the alternative for this method supported in latest version.
You'll likely want to set the allow_null=True. required=False will only work if the key isn't defined at all.
In the latest version, required=False fields are automatically excluded.
This is discussed in more detail in this (closed) issue.
I'd recommend updating to the latest version.

DateTimeField queryset returning None in Django

I am trying to create a queryset for getting the values of a DateTimeField which is DATETIME in the DB.
The class in models.py:
class ChangeMetrics(models.Model):
id = models.IntegerField(primary_key=True)
file_id = models.ForeignKey(File, db_column = 'file_id')
version_id = models.ForeignKey(Version, db_column = 'version_id')
function_id = models.ForeignKey(Function, blank=True, db_column = 'function_id')
date = models.DateTimeField(blank=True, null=True)
user = models.TextField(blank=True)
changed = models.IntegerField(blank=True, null=True)
The field in the DB:
date DATETIME
The tuples are populated in the database and running SQL queries directly on the DB is working perfectly.
This is the queryset I am currently using in Django:
queryset = ChangeMetrics.objects.filter(~Q(changed=None), ~Q(date=None), ~Q(version_id=None))
I have tried a raw query and also a version of the query that uses exclude(), but that still returns None for date.
I am accessing the entries in the queryset through a for loop and simply accessing date through entry.date inside the for loop.
Edit:
Django version 1.6.5
I have also tried getting the values through the Django shell, to no success.
Any ideas on what could be wrong?
not sure if you were able to figure this out, but I just had this problem and was able to fix it.
So, Django migrations were creating the column in the DB as datetime(6) instead of datetime. This was causing the Django models to fail to instantiate the Datetime object.
ALTER TABLE `my_table`
MODIFY COLUMN `created` datetime NOT NULL
After running that if fixed my issue. Maybe in your case you could try modifying to datetime(6) instead.
We had this same issue popup while pushing code from local environment (Mac OS X) up to App Engine. While altering the fields like Alexander mentioned to be DATETIME instead of DATETIME(6) did start making them appear, we lost the microseconds. Ended up realizing that in local environment we were running MySQLdb 1.2.5 but when deploying to App Engine, even though we had specified "latest" as the version of MySQLdb, it was only pulling 1.2.4b4, hard-coding to 1.2.5 fixed the issue.
Can you please try this solution:
queryset = list(ChangeMetrics.objects.filter(changed__isnull=False, date__isnull=False, version_id__isnull=False))
EDIT : Try to move the databse out of your folder, then run python manage.py syncdb and check if your database is created correctly according to the Models.
Doesn't work :
Maybe you can try with this (I don't know if it works, I can't try it now) :
queryset = ChangeMetrics.objects.filter(changed!=None, date!=None, version_id!=None)
This issue is caused by an outdated version of MySQL-python not by Django or migrations system.
Using mysqlclient (which is an updated fork of MySQL-python) solves this problem.
I guess you generate (django migrate command) your database schema on mac. Try to delete the schema and re-migrate from a windows machine.

should I use .rank or .order_id?

accessing order_id property of a ScoredDocument object in SearchResults object generates following error in log:
DeprecationWarning: order_id is deprecated; use rank instead
logging.debug(document.order_id)
However documentation here refers to order_id: https://developers.google.com/appengine/docs/python/search/scoreddocumentclass
Which is correct? I am using SDK 1.7.3.
Documentation updates slower then the code, you should flow whatever the latest code recommends you to do.
You should use rank. I've filed a bug to fix that documentation. (I work on the Search API)
In the SdkReleaseNotes of the version 1.6.6 - May22, 2012 it writes:
"The Search API has deprecated the order_id attribute on Document class. It has been replaced with the rank attribute."
So obviously you should use rank.

Why do I get an InvalidDocument exception when saving an object into MongoDB in Django for the first time?

I've been having a nightmare of a time trying to get MongoDB working with Django. I now have it successfully installed, but it errors upon the first attempt to save an object. I've been following this tutorial, and the Post model they present I have copied precisely.
Here is the code for the model:
from django.db import models
from djangotoolbox.fields import ListField
class Post(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
tags = ListField()
comments = ListField()
The post is actually created (and inserted) here:
post = Post.objects.create(
... title='Hello MongoDB!',
... text='Just wanted to drop a note from Django. Cya!',
... tags=['mongodb', 'django'],
... comments=['comment 1', 'comment 2']
... )
The full stack trace can be found here. The error itself is:
InvalidDocument: documents must have only string keys, key was <django.db.models.fields.CharField object at 0x22cae50>
Clearly MongoDB is functioning, because it wants the keys to be strings instead of integers. But why is the rum gone? Err, why are standard Django objects not able to save into the MongoDB database?
I have added the required CharField parameter max_length that was overlooked. It does not work in this case, nor does it if I also remove the lists.
I got this error until updating the django-mongodb-engine library to the current version in the 'develop' branch of the github repository. Simply using the instructions on the article shown will import the master branch.
I have also followed this tutorial and had same error. I managed to fix this problem.
What I did wrong is I used djangotoolbox from github (https://github.com/django-nonrel/djangotoolbox) repository, which was ver 0.9.2. Then I removed this and did it as tutorial states and used bitbucket (https://bitbucket.org/wkornewald/djangotoolbox) that is on ver 0.9.1 of djangotoolbox. Now it works fine.
Does this work:
post = Post(
... title='Hello MongoDB!',
... text='Just wanted to drop a note from Django. Cya!',
... tags=['mongodb', 'django'],
... comments=['comment 1', 'comment 2']
... )
Another thing to try:
class Post(models.Model):
title = models.CharField(primary_key=True, max_length=200)
I think by default Django uses auto-generated numeric values as primary keys. This would force your title to be your primary key... it's a char string, so it might solve the problem you're seeing. It's just a guess, because the actual error your seeing doesn't make too much sense to me.
From what I see, your model looks just fine. The error is funny; it is saying that the key to the attribute you are calling as "title" cannot be anything other than a string, but if I'm not mistaken, the string here is the key "title" and the value is the CharField() field, together representing a key/value pair in the Post document in your MongoDB. Try isolating the problem by jumping into the django shell:
python manage.py shell
and building your Post object from scratch. Use the model that dragonx has mentioned. Simple is best to debug these problems. If you are getting the same error when you try either to call Post.objects.create(p) for a Post object p, or when you call p.save(), try re-writing the Post model and give it another shot.
Finally, you can show us your settings.py file and see what your mongodb settings are there. If you say you are using django-nonrel, then there are basic checks you can make to ensure that python, django, and mongodb are talking to each other.
Let us know how you're doing.

Categories