Generating model one-to-one field with django-autofixtures - python

I'm trying to create fake data for my model which is linked to the auth.User. I'm running Python 3.7 with Django 2.1 django-autofixture 0.12.1:
models.py
Class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
about = models.CharField(max_length=200)
autofixtures.py
Class PersonGenerator(AutoFixture):
field_values = {
'user':InstanceGenerator(autofixture=UserFixture(User)),
'about': LoremGenerator(max_length=200)
}
register(Person,PersonGenerator)
Then I run the autofixtures file to register my generator
py manage.py shell
>>> exec(open('myapp/autofixtures.py').read())
>>> exit()
py manage.py loadtestdata myapp.Person:50
I've got the following error message:
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "D:\..\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "D:\..\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\..\env\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "D:\..\env\lib\site-packages\django\core\management\base.py", line 353, in execute
output = self.handle(*args, **options)
File "c:\..\local\programs\python\python37-32\Lib\contextlib.py", line 74, in inner
return func(*args, **kwds)
File "D:\..\env\lib\site-packages\autofixture\management\commands\loadtestdata.py", line 225, in handle
autofixture.create(model, count, **kwargs)
File "D:\..\env\lib\site-packages\autofixture\__init__.py", line 136, in create
return autofixture.create(count, **create_kwargs)
File "D:\..\env\lib\site-packages\autofixture\base.py", line 554, in create
instance = self.create_one(commit=commit, **kwargs)
File "D:\..\env\lib\site-packages\autofixture\base.py", line 501, in create_one
self.process_field(instance, field)
File "D:\..\env\lib\site-packages\autofixture\base.py", line 400, in process_field
value = self.get_value(field)
File "D:\..\env\lib\site-packages\autofixture\base.py", line 396, in get_value
value = generator()
File "D:\..\env\lib\site-packages\autofixture\generators.py", line 71, in __call__
return self.get_value()
File "D:\..\env\lib\site-packages\autofixture\generators.py", line 67, in get_value
value = self.generate()
File "D:\..\env\lib\site-packages\autofixture\generators.py", line 535, in generate
return self.autofixture.create()[0]
File "D:\..\env\lib\site-packages\autofixture\base.py", line 554, in create
instance = self.create_one(commit=commit, **kwargs)
File "D:\..\env\lib\site-packages\autofixture\base.py", line 526, in create_one
self.process_m2m(instance, field)
File "D:\..\env\lib\site-packages\autofixture\base.py", line 413, in process_m2m
return self.process_field(instance, field)
File "D:\..\env\lib\site-packages\autofixture\base.py", line 403, in process_field
setattr(instance, field.name, value)
File "D:\..\env\lib\site-packages\django\db\models\fields\related_descriptors.py", line 537, in __set__
% self._get_set_deprecation_msg_params(),
TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use groups.set() instead.
How can it be M2M set when my relationship is one-to-one?

So Django 2 does not allow creating foreign key without saving the instance first. I switched to factory boy and use their SubFactory feature for this and it works.

to fix error with many to many fields for django-autofixture in django 2 you can do it like this
class News(models.Model):
categories = models.ManyToManyField(Category, blank=True)
title = models.CharField(max_length=255)
class Category(models.Model):
title = models.CharField(max_length=255)
news = AutoFixture(News).Create(1, commit=False)
news.save()
news.categories.set([AutoFixture(Category).create_one()])

Related

Instance creation error when using factory_boy with mongoengine

I'm trying to use factory_boy for testing my mongoengine database operations. Here's the mongoengine documents:
import mongoengine
class Address(mongoengine.EmbeddedDocument):
street = mongoengine.StringField()
class Person(mongoengine.Document):
name = mongoengine.StringField()
address = mongoengine.EmbeddedDocumentField(Address)
Then I define the factory classes:
class AddressFactory(factory.mongoengine.MongoEngineFactory):
class Meta:
model = Address
street = factory.Sequence(lambda n: 'street%d' % n)
class PersonFactory(factory.mongoengine.MongoEngineFactory):
class Meta:
model = Person
name = factory.Sequence(lambda n: 'name%d' % n)
address = factory.SubFactory(AddressFactory)
And after I try to use them in test...
import unittest
class TestPerson(unittest.TestCase):
def test_person_creation(self):
person = PersonFactory.create()
assert models.Plan.objects.get(address=plan.address).first()
...and get the following exception which to me looks like if I have not defined the class of the document in meta.model part of my factory class but I did. I guess I'm using the create() method in a wrong way I'm just not sure how.
Traceback (most recent call last):
File "/home/anton/drill_ws/src/drill-hal/tests/test_store.py", line 76, in <module>
person = PersonFactory.create()
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/base.py", line 564, in create
return cls._generate(enums.CREATE_STRATEGY, kwargs)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/base.py", line 501, in _generate
return step.build()
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/builder.py", line 272, in build
step.resolve(pre)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/builder.py", line 221, in resolve
self.attributes[field_name] = getattr(self.stub, field_name)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/builder.py", line 375, in __getattr__
extra=context,
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/declarations.py", line 321, in evaluate
return self.generate(step, defaults)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/declarations.py", line 411, in generate
return step.recurse(subfactory, params, force_sequence=force_sequence)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/builder.py", line 233, in recurse
return builder.build(parent_step=self, force_sequence=force_sequence)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/builder.py", line 272, in build
step.resolve(pre)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/builder.py", line 221, in resolve
self.attributes[field_name] = getattr(self.stub, field_name)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/builder.py", line 375, in __getattr__
extra=context,
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/declarations.py", line 321, in evaluate
return self.generate(step, defaults)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/declarations.py", line 411, in generate
return step.recurse(subfactory, params, force_sequence=force_sequence)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/builder.py", line 233, in recurse
return builder.build(parent_step=self, force_sequence=force_sequence)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/builder.py", line 279, in build
kwargs=kwargs,
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/base.py", line 315, in instantiate
return self.factory._create(model, *args, **kwargs)
File "/home/anton/.local/share/virtualenvs/drill-hal-TAWOMXlQ/lib/python3.7/site-packages/factory/mongoengine.py", line 26, in _create
instance = model_class(*args, **kwargs)
TypeError: 'NoneType' object is not callable

Django - Celery ValueError: Related model u'user.User' cannot be resolved

When I am executing celery task it is giving me:
ValueError: Related model u'user.User' cannot be resolved
The stacktrace is
Traceback (most recent call last):
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/celery/app/trace.py", line 375, in trace_task
R = retval = fun(*args, **kwargs)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/celery/app/trace.py", line 632, in __protected_call__
return self.run(*args, **kwargs)
File "/Users/prince/work/magneto/set/facebook_pages/tasks.py", line 23, in analyze_page
connected_facebook_page = get_connected_facebook_page(connected_facebook_page_id)
File "/Users/prince/work/magneto/set/facebook_pages/utils.py", line 49, in get_connected_facebook_page
return ConnectedUserPage.objects.get(id=connected_facebook_page_id)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 374, in get
num = len(clone)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 232, in __len__
self._fetch_all()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 1118, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 876, in execute_sql
sql, params = self.as_sql()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 428, in as_sql
extra_select, order_by, group_by = self.pre_sql_setup()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 46, in pre_sql_setup
self.setup_query()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 37, in setup_query
self.select, self.klass_info, self.annotation_col_map = self.get_select()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 194, in get_select
for c in self.get_default_columns():
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 569, in get_default_columns
column = field.get_col(alias)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1008, in get_col
return super(ForeignKey, self).get_col(alias, output_field or self.target_field)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 909, in target_field
return self.foreign_related_fields[0]
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 653, in foreign_related_fields
return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field)
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 640, in related_fields
self._related_fields = self.resolve_related_fields()
File "/Users/prince/virtualenvs/set/lib/python2.7/site-packages/django/db/models/fields/related.py", line 625, in resolve_related_fields
raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
ValueError: Related model u'user.User' cannot be resolved
Here ConnectedUserPage is a model with schema:
class ConnectedUserPage(TimeStampedModel):
user = models.ForeignKey('user.User', on_delete=models.PROTECT)
page = models.ForeignKey(FacebookPage, on_delete=models.PROTECT)
page_details = jsonb.JSONField()
My versions are :
celery==4.1.1
django-celery-beat==1.1.1
django-celery-results==1.0.1
Django==1.11.13
In case I directly import User model from user app I am getting stuck in circular imports.
Any help would be appreciated, stuck in this loop for a quite while now.
Where's User defined? Is this Django's own user model? If that's the case you can use User model directly:
from django.contrib.auth import get_user_model
User = get_user_model()
class ConnectedUserPage(TimeStampedModel):
user = models.ForeignKey(User, unique=True)
or you can also do
from django.conf import settings
class ConnectedUserPage(TimeStampedModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
If it is your own supplied User model, are you sure user is in INSTALLED_APPS?

Creating a callable function to generate a value for an attribute in django models

I have a model A which has a models.PositiveIntegerField() value and I need to generate the value for this attribute using some information that I get from another related model B.
class A(models.Model):
....
num = models.PositiveIntegerField()
....
def get_val(instance):
return instance.a.num + 1
Class B(models.Model):
...
a = models.ForeignKey(A, on_delete=models.CASCADE)
val = models.PositiveIntegerField(default=get_val)
...
But the mentioned approach is not working and is giving me this error while trying to do python manage.py migrate after doing python manage.py makemigrations
TypeError: get_val() missing 1 required positional argument: 'instance'
Error in detail:
Applying problemsetting.0011_testcase_index...Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
output = self.handle(*args, **options)
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle
fake_initial=fake_initial,
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/db/migrations/migration.py", line 122, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards
field,
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 306, in add_field
self._remake_table(model, create_field=field)
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/db/backends/sqlite3/schema.py", line 178, in _remake_table
self.effective_default(create_field)
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 218, in effective_default
default = field.get_default()
File "/mnt/ebram96/workspace/linux/django_projects/env3/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 775, in get_default
return self._get_default()
TypeError: get_val() missing 1 required positional argument: 'instance'
I'm using python 3 and django 2 under a virtual environment..
if you want to get a value by the instance, you can override the save method:
Class B(models.Model):
...
a = models.ForeignKey(A, on_delete=models.CASCADE)
val = models.PositiveIntegerField()
# ^^^
def save(self, *args, **kwargs):
if not self.val:
self.val = self.a.num + 1
return super().save(*args, **kwargs)
more details you can read overriding-predefined-model-methods

How to create self-referencing EndpointsModel

I'm trying to create following self-referencing EndpointsModel (the trick with _fix_up_properties() is taken from here: https://groups.google.com/forum/#!topic/appengine-ndb-discuss/1FmgEVK7JNM):
class EventFieldSchema(EndpointsModel):
name = ndb.StringProperty(required=True)
type = msgprop.EnumProperty(EventType, required=True)
EventFieldSchema.nested_fields = ndb.LocalStructuredProperty(EventFieldSchema,repeated=True)
EventFieldSchema._fix_up_properties()
This works for datastore model, but unfortunately, the nested_fields field won't be included into ProtoRPC message.
I've tried to manually specify message fields schema, by adding at the end following line:
EventFieldSchema._message_fields_schema = ('name', 'type', 'nested_fields')
but then app-engine fails, going into a loop, trying turn EventFieldSchema into ProtoRPC field:
Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/main.py", line 3, in <module>
from er.api.event import EventRegistryApi
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/er/api/event.py", line 17, in <module>
class EventRegistryApi(remote.Service):
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/er/api/event.py", line 23, in EventRegistryApi
name='%s.insert' % RESOURCE_NAME)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/protorpc-1.0/protorpc/util.py", line 170, in positional_wrapper
return wrapped(*args, **kwargs)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 1359, in method
kwargs[REQUEST_MESSAGE] = cls.ProtoModel(fields=request_fields)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 1031, in ProtoModel
allow_message_fields=allow_message_fields)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 969, in _MessageFields
proto_attr = to_proto(prop, field_index)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/utils.py", line 137, in StructuredPropertyToProto
property_proto = property_proto_method()
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 1031, in ProtoModel
allow_message_fields=allow_message_fields)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 969, in _MessageFields
proto_attr = to_proto(prop, field_index)
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/utils.py", line 137, in StructuredPropertyToProto
property_proto = property_proto_method()
File "/base/data/home/apps/s~project/eventregistry:dev.380885914276541023/endpoints_proto_datastore/ndb/model.py", line 1031, in ProtoModel
Is this a bug in EndpointsModel? What is the "proper" way of defining self-referencing EndpointsModels?
Having the same issue with self-referencing an EndpointsModel:
class UnitsProtoModel(EndpointsModel):
""" ProtoRPC Model for storing/retrieving a unit. """
_message_fields_schema = ('id', 'uic', 'parent_id', 'branch_id', 'name')
uic = ndb.StringProperty(required=True)
parent_id = ndb.StringProperty(required=True, default=None)
branch_id = ndb.StringProperty(required=True)
name = ndb.StringProperty(required=True)
abbreviated_name = ndb.StringProperty(default="")
flagged = ndb.BooleanProperty(default=False)
message = ndb.StringProperty(default="")
unit_created_at = ndb.DateTimeProperty(auto_now_add=True)
class UnitsCollection(EndpointsModel):
items = messages.MessageField(UnitsProtoModel, 1, repeated=True)
Error msg:
`File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine- default.bundle/Contents/Resources/google_appengine/lib/protorpc-1.0/protorpc/util.py", line 170, in positional_wrapper
return wrapped(*args, **kwargs)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/protorpc-1.0/protorpc/messages.py", line 1531, in init
raise FieldDefinitionError('Invalid message class: %s' % message_type)
FieldDefinitionError: Invalid message class:
UnitsProtoModel<abbreviated_name=StringProperty('abbreviated_name', default=''), branch_id=StringProperty('branch_id', required=True), flagged=BooleanProperty('flagged', default=False), message=StringProperty('message', default=''), name=StringProperty('name', required=True), owner=UserProperty('owner'), parent_id=StringProperty('parent_id', required=True), uic=StringProperty('uic', required=True), unit_created_at=DateTimeProperty('unit_created_at', auto_now_add=True)>`

PyAMF DatabaseError: 'This query is not supported by the database.' when returning the User object

This is the error I'm getting:
ERROR 2011-11-19 04:19:55,441 django.py:164] Error encoding AMF request
Traceback (most recent call last):
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/remoting/gateway/django.py", line 161, in __call__
logger=self.logger, timezone_offset=timezone_offset)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/remoting/__init__.py", line 676, in encode
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/remoting/__init__.py", line 520, in _write_body
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/remoting/__init__.py", line 486, in _encode_body
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/codec.py", line 499, in writeElement
func(data)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/amf0.py", line 657, in writeAMF3
self.context.getAMF3Encoder(self).writeElement(data)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/codec.py", line 499, in writeElement
func(data)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/amf3.py", line 1456, in writeObject
self.writeElement(value)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/codec.py", line 499, in writeElement
func(data)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/amf3.py", line 1298, in writeList
[self.writeElement(x) for x in n]
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/codec.py", line 499, in writeElement
func(data)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/codec.py", line 358, in __call__
ret = self.func(data, encoder=self.encoder)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/adapters/_django_db_models_base.py", line 276, in writeDjangoObject
encoder.writeObject(referenced_object)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/amf3.py", line 1468, in writeObject
self.writeElement(value)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/codec.py", line 499, in writeElement
func(data)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/codec.py", line 358, in __call__
ret = self.func(data, encoder=self.encoder)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/adapters/_django_db_models_base.py", line 276, in writeDjangoObject
encoder.writeObject(referenced_object)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/amf3.py", line 1468, in writeObject
self.writeElement(value)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/codec.py", line 499, in writeElement
func(data)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/codec.py", line 358, in __call__
ret = self.func(data, encoder=self.encoder)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/adapters/_django_db_models_base.py", line 276, in writeDjangoObject
encoder.writeObject(referenced_object)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/amf3.py", line 1447, in writeObject
attrs = alias.getEncodableAttributes(obj, codec=self)
File "/Library/Python/2.6/site-packages/PyAMF-0.6.1-py2.6-macosx-10.6-universal.egg/pyamf/adapters/_django_db_models_base.py", line 173, in getEncodableAttributes
attrs[name] = [x for x in getattr(obj, name).all()]
File "/Users/bryce/Documents/Aptana Studio 3 Workspace/django-blog/django/db/models/query.py", line 107, in _result_iter
self._fill_cache()
File "/Users/bryce/Documents/Aptana Studio 3 Workspace/django-blog/django/db/models/query.py", line 774, in _fill_cache
self._result_cache.append(self._iter.next())
File "/Users/bryce/Documents/Aptana Studio 3 Workspace/django-blog/django/db/models/query.py", line 275, in iterator
for row in compiler.results_iter():
File "/Users/bryce/Documents/Aptana Studio 3 Workspace/DennysBE/djangotoolbox/db/basecompiler.py", line 225, in results_iter
self.check_query()
File "/Users/bryce/Documents/Aptana Studio 3 Workspace/DennysBE/djangotoolbox/db/basecompiler.py", line 273, in check_query
raise DatabaseError('This query is not supported by the database.')
DatabaseError: This query is not supported by the database.
Here are my models that matter for this problem:
class ChallengeAct(models.Model):
challenge = models.ForeignKey(Challenge, blank=True, null=True)
user = models.ForeignKey(User, blank=True, null=True)
start_date = models.DateTimeField(blank=True, null=True)
progress_value = models.IntegerField(default=0)
earned_coupon = models.ForeignKey(EarnedCoupon, blank=True, null=True)
Here is the method that causes the error:
def foo_bar(request):
user = request.user
c = ChallengeAct()
c.challenge = Challenge.objects.get(id=1)
c.start_date = datetime.now()
c.progress_value = 1
c.user = user
c.save()
# Here is where I set the user to null to avoid the DatabaseError
c.user = None
return [c]
The interesting thing is that I need to set the c.user = None right before I return it so I don't get the DatabaseError: This query is not supported by the database. problem.
--update-- The more I think about it, it seems like a pyamf and django-nonrel problem with getting the user object. I'm guessing that when pyamf tries to get the user object it is using some type of join query, which isn't supported on django-nonrel.
Why is this? Is there a way around it?
You should not have to to allow for blank=True, null=True for User model. Normally django.contrib.auth.models.AnonymousUser takes care of anonymous requests. It may or may not fix the issue, but it is worth trying, i.e.:
class ChallengeAct(RewardActBase):
user = models.ForeignKey(User)
....

Categories