Code


Version 12 (modified by ejf-django@…, 8 years ago) (diff)

Added pitfall about forgetting to update all in model's init.py

Common Pitfalls - Data Models

If you encounter a strange error, make sure to run django-admin.py validate. That catches some common errors in model syntax.

ManyToManyField

Name likeness of helper classes and field classes

Warning

The field class is ManyToManyField, not ManyToMany. The latter is for internal use only.

Symptoms

A traceback that talks about __init__ getting 2 instead of 3 required positional parameters in the line of your model where the fields tuple is built.

ImageFields/FileFields

Providing an image field in without media configured

Warning

If you have an ImageField in your model, you need to configure media. See How do I use image and file fields? in the FAQ.

Symptoms

Data not being posted to the database with a refresh of the "add" screen.

Using module globals in models

The model module, being a Python module, can import stuff or define globals. You might want to use those globals or imported modules in your models classes methods like this:

import md5

class Something(meta.Model):
    def func(self, parm):
        md5.new()

Warning

If you import modules in your model files, or if you define globals in your model file and want to use them in methods of the model classes, you need to define module_constants and pass along those globals you wish to use in the model. This happens because every model class is turned into a virtual module that doesn't automatically inherit all global values from your model file. Do it like this:

import md5

class Something(meta.Model):
    class META:
        module_constants = {
            'md5': md5
        }
    def func(self, parm):
          md5.new()

Or, you can simply import the modules needed in the function itself:

class Something(meta.Model):
    ...
    def func(self):
        import md5
        md5.new(...)

More information.

Symptoms

You get tracebacks with NameErrors in your modules as if the global wasn't there.

If You Find get_X_list, get_X_count, etc. Not Getting Created

If you have a model class (for example Choices) that has a ForeignKey, the class that is the foreign key (for example Polls) gets methods like get_X_list, get_X_count (for example, Polls.get_choice_list, Polls.get_choice_count).

However, if you find those are not getting created, and you have a multi-file model, check to make sure that you have updated the all variable in your model's init.py. It can be tough to remember to update that with the list of all your files in your model. If a particular model file isn't in all, those methods won't get created in your model objects.