To explain the error - code that is not inside a function, such as the line in your question, is executed as soon as your models.py
file is loaded by Python. This happens early in the start-up of your Django process, when Django looks for a models.py file in each of the INSTALLED_APPS
and imports it. The problem is that you don't know which other models have been imported yet. The error here is because the Group
model (from django.auth.models
) has not been imported yet, so it is as if it doesn't exist (yet).
Others have suggested you could put the Group.objects.get_or_create(name="Free")[0]
in a function so that it is not executed immediately, Django will instead call the function only when it needs to know the value. At this point all the models in your project, and Django's own models, will have been imported and it will work.
Regarding the second part of your question... yes, any time you use get
or get_or_create
methods you need to query on a unique field otherwise you may get MultipleObjectsReturned
exception.
In fact I think you should not use get_or_create
for what you are trying to do here. Instead you should use an initial data fixture:
https://docs.djangoproject.com/en/1.9/howto/initial-data/
...to ensure that the default group already exists (and with a known primary key value) before you run your site.
That way you will know the unique pk
of the default Group
and you can do a get
query:
def default_group():
return Group.objects.get(pk=1)
class YourModel(models.model):
group = models.ForeignKey(Group, default=default_group)