Django Haystack update index faster - django

I've been using Django Haystack for a while now and it's great! I have a rather heavy site with data which needs to be updated from time to time (15 to 30 mins).
When using the python manage.py update_index it takes lots of time to update the data. Is there a way to speed this up? Or maybe update only changed data if possible..
I'm currently using Django Haystack 1.2.7 with Solr as backend and Django 1.4.
Thanks!!!
EDIT:
Yes I've tried reading that part of the documentation but what I really need is a way to speed the indexing up. Maybe update only recent data instead of updating all. I've found get_updated_field but don't know how to use it. In the documentation it's only mentioned why it's used but no real examples are shown.
EDIT 2:
start = DateTimeField(model_attr='start', null=True, faceted=True, --HERE?--)
EDIT 3:
Ok i've implemented the solution bellow but when i tried rebuild_index (with 45000 data) it almost crashed my computer. After 10 mins of waiting an error appeared:
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/rebuild_index.py", line 16, in handle
call_command('update_index', **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 150, in call_command
return klass.execute(*args, **defaults)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/update_index.py", line 193, in handle
return super(Command, self).handle(*apps, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 304, in handle
app_output = self.handle_app(app, **options)
File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/update_index.py", line 229, in handle_app
do_update(index, qs, start, end, total, self.verbosity)
File "/usr/local/lib/python2.7/dist-packages/haystack/management/commands/update_index.py", line 109, in do_update
index.backend.update(index, current_qs)
File "/usr/local/lib/python2.7/dist-packages/haystack/backends/solr_backend.py", line 73, in update
self.conn.add(docs, commit=commit, boost=index.get_field_weights())
File "/usr/local/lib/python2.7/dist-packages/pysolr.py", line 686, in add
m = ET.tostring(message, encoding='utf-8')
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1127, in tostring
ElementTree(element).write(file, encoding, method=method)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 821, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 940, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 940, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 915, in _serialize_xml
write("<" + tag)
MemoryError

get_updated_field should return a string that contains the name of the attribute on the model that contains the date that the model was updated (haystack docs). A DateField with auto_now=True would be ideal for that (Django docs).
For example, my UserProfile model has a field named updated
models.py
class UserProfile(models.Model):
user = models.ForeignKey(User)
# lots of other fields snipped
updated = models.DateTimeField(auto_now=True)
search_indexes.py
class UserProfileIndex(SearchIndex):
text = CharField(document=True, use_template=True)
user = CharField(model_attr='user')
user_fullname = CharField(model_attr='user__get_full_name')
def get_model(self):
return UserProfile
def get_updated_field(self):
return "updated"
Then when I run ./manage.py update_index --age=10 it only indexes the user profiles updated in the last 10 hours.

Related

Adding custom QuerySet to UserModel causes makemigrations exception

I would like to create a custom queryset for my User model.
However, I cannot simply use objects = UserQuerySet.as_manager() since the standard Django User model already has a custom UserManager.
My code is simply :
class UserQuerySet(MyBaseQuerySet):
def opted_out_method(self):
return
class User(AbstractUser):
objects = UserManager.from_queryset(UserQuerySet)()
# etc...
This code works, except when I do this:
$manage.py makemigrations --dry-run
File "./manage.py", line 49, in <module>
execute_from_command_line(sys.argv)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 164, in handle
changes = autodetector.changes(
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/autodetector.py", line 43, in changes
changes = self._detect_changes(convert_apps, graph)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/autodetector.py", line 129, in _detect_changes
self.new_apps = self.to_state.apps
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/utils/functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 210, in apps
return StateApps(self.real_apps, self.models)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 273, in __init__
self.render_multiple([*models.values(), *self.real_models])
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 308, in render_multiple
model.render(self)
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 577, in render
body.update(self.construct_managers())
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/migrations/state.py", line 536, in construct_managers
as_manager, manager_path, qs_path, args, kwargs = manager.deconstruct()
File "/home/user/.cache/pypoetry/virtualenvs/django-app-4WxKU_E8-py3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 61, in deconstruct
raise ValueError(
The exception raised is "Could not find manager. Please note that you need to inherit from managers you dynamically generated with 'from_queryset()", which is what I'm doing.
Has anyone run into this before?
I'm currently using Django 2.2, not sure if this is fixed in 3+.
The solution is to create a custom manager that derives from UserManager.
from django.contrib.auth.models import UserManager
class MyCustomUserManager(UserManager):
def bob_filter(self):
return super().get_queryset().filter(first_name__icontains="bob")
# etc...
class User(AbstractUser):
objects = managers.CustomUserManager()
# etc...

Phantom ForeignKey to similar model representing a DB view

I'm trying to get this 'phantom' ForeignKey to reference a model that is a view on the backend. The view assembles data that includes some data from the originating table(so they share a primary key).
Here's a simplified version of what we've had to setup(view is more complex than just the model, so it was chosen to design it this way).
class VSpouse(models.Model):
person_id = models.IntegerField(primary_key=True)
...
class Person(models.Model):
person_id = models.AutoField(primary_key=True)
spouse = models.ForeignKey(VSpouse, db_column = 'person_id', to_field='person_id', null=True)
...
Now, since the tables were designed on the backend before models, we have never used syncdb. Because of that, we've never noticed a problem and things work just as expected.
However, now we're starting to develop some Django tests, and when it begins to build the test DB, we see the following:
$ python2 manage.py test misc --traceback
Creating test database for alias 'default'...
Destroying old test database 'default'...
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 222, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/lib/python2.7/site-packages/django/core/management/commands/test.py", line 72, in execute
super(Command, self).execute(*args, **options)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 255, in execute
output = self.handle(*args, **options)
File "/usr/lib/python2.7/site-packages/django/core/management/commands/test.py", line 89, in handle
failures = test_runner.run_tests(test_labels)
File "/usr/lib/python2.7/site-packages/django/test/simple.py", line 367, in run_tests
old_config = self.setup_databases()
File "/usr/lib/python2.7/site-packages/django/test/simple.py", line 315, in setup_databases
self.verbosity, autoclobber=not self.interactive)
File "/usr/lib/python2.7/site-packages/django/db/backends/creation.py", line 293, in create_test_db
load_initial_data=False)
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 161, in call_command
return klass.execute(*args, **defaults)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 255, in execute
output = self.handle(*args, **options)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 385, in handle
return self.handle_noargs(**options)
File "/usr/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 102, in handle_noargs
cursor.execute(statement)
File "/usr/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 58, in execute
six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
File "/usr/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 54, in execute
return self.cursor.execute(query, args)
DatabaseError: column "person_id" specified more than once
Now, I guess my question is, is there any 'proper' ways of doing this or working around this problem? It would be great if I could just add a switch like real=False to the field definition so it wouldn't try and generate the column when building the test DB. However, I don't think that's currently possible.
Actually, you can. Only it's not called real, but abstract, and it applies to models (but you should be able to use inheritance to address this).
Your model structure might need a little massaging to correspond to what Django expects, but that should get you started in the right direction.
It's documented here.

ValidationError during Django-South migration

So, I am learning to use South and I've been running in a few issues. I did the initial app migration with the model looking like this:
class Poll(models.Model):
pass
Then added my fields...
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField()
and during the migration South complained that those fields didn't have a default, so I entered some but it didn't work... now when I try deleting them from the model and migrating back to the empty mode I get the following traceback:
mirkocrocop#Mirkos-MacBook-Pro:~/workspace/toastdriven$ python manage.py migrate polls
Running migrations for polls:
- Migrating forwards to 0007_auto__del_field_poll_question.
> polls:0003_auto__add_field_poll_question__add_field_poll_pub_date
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/management/commands/migrate.py", line 108, in handle
ignore_ghosts = ignore_ghosts,
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/__init__.py", line 213, in migrate_app
success = migrator.migrate_many(target, workplan, database)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 235, in migrate_many
result = migrator.__class__.migrate_many(migrator, target, migrations, database)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 310, in migrate_many
result = self.migrate(migration, database)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 133, in migrate
result = self.run(migration)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 106, in run
dry_run.run_migration(migration)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 191, in run_migration
self._run_migration(migration)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 178, in _run_migration
raise exceptions.FailedDryRun(migration, sys.exc_info())
south.exceptions.FailedDryRun: ! Error found during dry run of '0003_auto__add_field_poll_question__add_field_poll_pub_date'! Aborting.
Traceback (most recent call last):
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 175, in _run_migration
migration_function()
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/migration/migrators.py", line 57, in <lambda>
return (lambda: direction(orm))
File "/Users/mirkocrocop/workspace/toastdriven/polls/migrations/0003_auto__add_field_poll_question__add_field_poll_pub_date.py", line 19, in forwards
keep_default=False)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/db/sqlite3.py", line 31, in add_column
field.column: self._column_sql_for_create(table_name, name, field, False),
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/db/sqlite3.py", line 189, in _column_sql_for_create
sql = self.column_sql(table_name, name, field, with_name=False, field_prepared=True)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/south/db/generic.py", line 688, in column_sql
default = field.get_db_prep_save(default, connection=self._get_connection())
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 292, in get_db_prep_save
prepared=False)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 816, in get_db_prep_value
value = self.get_prep_value(value)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 801, in get_prep_value
value = self.to_python(value)
File "/Users/mirkocrocop/.virtualenvs/toastdriven/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 785, in to_python
raise exceptions.ValidationError(msg)
ValidationError: [u"'0' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]
How could I fix this, and what is the correct way of adding these fields + doing the migration from the empty model to the field populated model? I've been going through South's docs but I don't get it... I did everything according to the documentation, but I'm not sure what should I default the DateTimeField to...
At the time you have to provide a default value, you are interacting with a python interpreter. As it is mentioned, the datetime module is available at that point in time. To provide a default for a DateTimeField in this case, just provide a datetime object:
# Use the current date and time
datetime.datetime.now()
# Or a specific date and time
datetime.datetime(2012, 10, 1, 17, 30, 0, 0)

django-haystack - Updating index after adding new field to index causing error

I have a django site which uses Haystack with the Xapian backend for search indexing. I've added a new field to one of the models being indexed, then added that field to the SearchIndex for that model. I've run:
python manage.py update_index
To update the index, but I'm getting the following error:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 220, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.6/dist-packages/django_haystack-1.0.1_final-py2.6.egg/haystack/management/commands/update_index.py", line 51, in handle
self.handle_app(None, **options)
File "/usr/local/lib/python2.6/dist-packages/django_haystack-1.0.1_final-py2.6.egg/haystack/management/commands/update_index.py", line 107, in handle_app
index.backend.update(index, small_cache_qs[start:end])
File "/usr/local/lib/python2.6/dist-packages/xapian_haystack-1.1.3beta-py2.6.egg/xapian_backend.py", line 204, in update
data = index.prepare(obj)
File "/usr/local/lib/python2.6/dist-packages/django_haystack-1.0.1_final-py2.6.egg/haystack/indexes.py", line 102, in prepare
self.prepared_data[field_name] = field.prepare(obj)
File "/usr/local/lib/python2.6/dist-packages/django_haystack-1.0.1_final-py2.6.egg/haystack/fields.py", line 119, in prepare
return self.convert(super(CharField, self).prepare(obj))
File "/usr/local/lib/python2.6/dist-packages/django_haystack-1.0.1_final-py2.6.egg/haystack/fields.py", line 75, in prepare
raise SearchFieldError("The model '%s' has an empty model_attr '%s' and doesn't allow a default or null value." % (repr(current_object), attr))
haystack.exceptions.SearchFieldError: The model 'None' has an empty model_attr 'address_county' and doesn't allow a default or null value.
The versions I'm using are django 1.2 and django-haystack 1.0.1. Upgrading these to the newest version isn't an option for me at the moment.
I found the answer. The clue was in the error message (which, as we all know, doesn't always happen!):
The model 'None' has an empty model_attr 'address_county' and doesn't allow a default or null value.
My model field had been created with blank=True, null=True. This caused the error, so I removed those and added default='' and this enabled me to update the index with no error. Hope this helps someone sometime!
I was facing the same issue when indexing the phone field of my modal. I simply add null=True to the solr field in search_index.py
phone = CharField(model_attr="phone", null=True)

Django Model SyncDB fail on the choices attribute due to a DB error

Here is a little error I get when trying to use syncdb on my django project.
Error:
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 219, in execute
self.validate()
File "/usr/local/lib/python2.6/dist-packages/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/usr/local/lib/python2.6/dist-packages/django/core/management/validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 146, in get_app_errors
self._populate()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/opt/admin-site/adminsite/cfadmin/models.py", line 111, in <module>
class RequestLog(models.Model):
File "/opt/admin-site/adminsite/cfadmin/models.py", line 117, in RequestLog
profile = models.PositiveIntegerField(null=True,blank=True, choices=get_profiles()) # It cannot be a foreign key this is not on the same DB
File "/opt/admin-site/adminsite/cfadmin/models.py", line 107, in get_profiles
cache.set('profiles_choices', profiles_choices, 3600)
File "/usr/local/lib/python2.6/dist-packages/django/core/cache/backends/locmem.py", line 83, in set
self._set(key, pickle.dumps(value), timeout)
File "/usr/lib/python2.6/copy_reg.py", line 84, in _reduce_ex
dict = getstate()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 61, in __getstate__
len(self)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 81, in __len__
self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 947, in iterator
for row in self.query.get_compiler(self.db).results_iter():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 672, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 727, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute
return self.cursor.execute(query, args)
django.db.utils.DatabaseError: relation "cfadmin_profile" does not exist
LINE 1: ...dmin_profile"."id", "cfadmin_profile"."name" FROM "cfadmin_p...
The models:
class Profile(models.Model):
name = models.CharField(max_length=256)
categories = models.ManyToManyField(Category)
def __unicode__(self):
return self.name
class Meta():
ordering = ["name"]
def get_profiles():
profiles_choices = cache.get('profiles_choices')
if profiles_choices == None:
try:
profiles_choices = Profile.objects.values_list('id','name')
cache.set('profiles_choices', profiles_choices, 3600)
except:
logging.info("Failed to retrieve the profile choices.")
pass
return profiles_choices
class Log(models.Model):
domain = models.CharField(max_length=512)
profile = models.PositiveIntegerField(null=True,blank=True, choices=get_profiles()) # this is where I get the error on Syncdb
def __unicode__(self):
return self.domain
class Meta():
ordering = ["domain"]
So if I am syncing a new project I will get the error that I mentioned earlier.
If I remove the call to my function get_profiles() in the model choices, it will synchronize with no error.
But I don't understand why I'm still getting the error even do I put a try catch within the function.
So in case of an error I would expect that it continues but instead it's completely aborting the syncdb.
Is there anyway to achieve what I'm trying to without removing the function and the put it back?
Thank you!
From the django doc " ... if you find yourself hacking choices to be dynamic, you're probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn't change much, if ever."
So you are probably better of changing your profile field in the Log model:
profile = models.ForeignKey(Profile, null=True,blank=True)
This is not the way to get choices for a model. Even if you fix your circular dependency problem, you will still have the issue that the get_choices() function will be called when the server process starts, and won't change in the meantime. Unlike default, I don't believe choices can be a callable.