1
0
mirror of https://github.com/django/django.git synced 2025-06-05 03:29:12 +00:00

magic-removal: Moved django.core.meta to django.db.models

git-svn-id: http://code.djangoproject.com/svn/django/branches/magic-removal@1631 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty 2005-12-14 05:02:51 +00:00
parent 55933c86e7
commit d0fabc0499
39 changed files with 338 additions and 331 deletions

View File

@ -1,3 +1,3 @@
from django.core import meta from django.db import models
# Create your models here. # Create your models here.

View File

@ -6,7 +6,7 @@ Each filter subclass knows how to display a filter for a field that passes a
certain test -- e.g. being a DateField or ForeignKey. certain test -- e.g. being a DateField or ForeignKey.
""" """
from django.core import meta from django.db import models
import datetime import datetime
class FilterSpec(object): class FilterSpec(object):
@ -50,7 +50,7 @@ class FilterSpec(object):
class RelatedFilterSpec(FilterSpec): class RelatedFilterSpec(FilterSpec):
def __init__(self, f, request, params): def __init__(self, f, request, params):
super(RelatedFilterSpec, self).__init__(f, request, params) super(RelatedFilterSpec, self).__init__(f, request, params)
if isinstance(f, meta.ManyToManyField): if isinstance(f, models.ManyToManyField):
self.lookup_title = f.rel.to._meta.verbose_name self.lookup_title = f.rel.to._meta.verbose_name
else: else:
self.lookup_title = f.verbose_name self.lookup_title = f.verbose_name
@ -103,7 +103,7 @@ class DateFieldFilterSpec(FilterSpec):
today = datetime.date.today() today = datetime.date.today()
one_week_ago = today - datetime.timedelta(days=7) one_week_ago = today - datetime.timedelta(days=7)
today_str = isinstance(self.field, meta.DateTimeField) and today.strftime('%Y-%m-%d 23:59:59') or today.strftime('%Y-%m-%d') today_str = isinstance(self.field, models.DateTimeField) and today.strftime('%Y-%m-%d 23:59:59') or today.strftime('%Y-%m-%d')
self.links = ( self.links = (
(_('Any date'), {}), (_('Any date'), {}),
@ -126,7 +126,7 @@ class DateFieldFilterSpec(FilterSpec):
'query_string': cl.get_query_string( param_dict, self.field_generic), 'query_string': cl.get_query_string( param_dict, self.field_generic),
'display': title} 'display': title}
FilterSpec.register(lambda f: isinstance(f, meta.DateField), DateFieldFilterSpec) FilterSpec.register(lambda f: isinstance(f, models.DateField), DateFieldFilterSpec)
class BooleanFieldFilterSpec(FilterSpec): class BooleanFieldFilterSpec(FilterSpec):
def __init__(self, f, request, params): def __init__(self, f, request, params):
@ -144,9 +144,9 @@ class BooleanFieldFilterSpec(FilterSpec):
yield {'selected': self.lookup_val == v and not self.lookup_val2, yield {'selected': self.lookup_val == v and not self.lookup_val2,
'query_string': cl.get_query_string( {self.lookup_kwarg: v}, [self.lookup_kwarg2]), 'query_string': cl.get_query_string( {self.lookup_kwarg: v}, [self.lookup_kwarg2]),
'display': k} 'display': k}
if isinstance(self.field, meta.NullBooleanField): if isinstance(self.field, models.NullBooleanField):
yield {'selected': self.lookup_val2 == 'True', yield {'selected': self.lookup_val2 == 'True',
'query_string': cl.get_query_string( {self.lookup_kwarg2: 'True'}, [self.lookup_kwarg]), 'query_string': cl.get_query_string( {self.lookup_kwarg2: 'True'}, [self.lookup_kwarg]),
'display': _('Unknown')} 'display': _('Unknown')}
FilterSpec.register(lambda f: isinstance(f, meta.BooleanField) or isinstance(f, meta.NullBooleanField), BooleanFieldFilterSpec) FilterSpec.register(lambda f: isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField), BooleanFieldFilterSpec)

View File

@ -1,17 +1,16 @@
from django.core import meta from django.db import models
from django.models import auth, core from django.models import auth, core
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
class LogEntry(meta.Model): class LogEntry(models.Model):
action_time = meta.DateTimeField(_('action time'), auto_now=True) action_time = models.DateTimeField(_('action time'), auto_now=True)
user = meta.ForeignKey(auth.User) user = models.ForeignKey(auth.User)
content_type = meta.ForeignKey(core.ContentType, blank=True, null=True) content_type = models.ForeignKey(core.ContentType, blank=True, null=True)
object_id = meta.TextField(_('object id'), blank=True, null=True) object_id = models.TextField(_('object id'), blank=True, null=True)
object_repr = meta.CharField(_('object repr'), maxlength=200) object_repr = models.CharField(_('object repr'), maxlength=200)
action_flag = meta.PositiveSmallIntegerField(_('action flag')) action_flag = models.PositiveSmallIntegerField(_('action flag'))
change_message = meta.TextField(_('change message'), blank=True) change_message = models.TextField(_('change message'), blank=True)
class META: class META:
module_name = 'log'
verbose_name = _('log entry') verbose_name = _('log entry')
verbose_name_plural = _('log entries') verbose_name_plural = _('log entries')
db_table = 'django_admin_log' db_table = 'django_admin_log'

View File

@ -1,8 +1,9 @@
from django.contrib.admin.views.main import MAX_SHOW_ALL_ALLOWED, DEFAULT_RESULTS_PER_PAGE, ALL_VAR from django.contrib.admin.views.main import MAX_SHOW_ALL_ALLOWED, DEFAULT_RESULTS_PER_PAGE, ALL_VAR
from django.contrib.admin.views.main import ORDER_VAR, ORDER_TYPE_VAR, PAGE_VAR, SEARCH_VAR from django.contrib.admin.views.main import ORDER_VAR, ORDER_TYPE_VAR, PAGE_VAR, SEARCH_VAR
from django.contrib.admin.views.main import IS_POPUP_VAR, EMPTY_CHANGELIST_VALUE, MONTHS from django.contrib.admin.views.main import IS_POPUP_VAR, EMPTY_CHANGELIST_VALUE, MONTHS
from django.core import meta, template from django.core import template
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils import dateformat from django.utils import dateformat
from django.utils.html import strip_tags, escape from django.utils.html import strip_tags, escape
from django.utils.text import capfirst from django.utils.text import capfirst
@ -74,7 +75,7 @@ def result_headers(cl):
for i, field_name in enumerate(lookup_opts.admin.list_display): for i, field_name in enumerate(lookup_opts.admin.list_display):
try: try:
f = lookup_opts.get_field(field_name) f = lookup_opts.get_field(field_name)
except meta.FieldDoesNotExist: except models.FieldDoesNotExist:
# For non-field list_display values, check for the function # For non-field list_display values, check for the function
# attribute "short_description". If that doesn't exist, fall # attribute "short_description". If that doesn't exist, fall
# back to the method name. And __repr__ is a special-case. # back to the method name. And __repr__ is a special-case.
@ -89,7 +90,7 @@ def result_headers(cl):
# Non-field list_display values don't get ordering capability. # Non-field list_display values don't get ordering capability.
yield {"text": header} yield {"text": header}
else: else:
if isinstance(f.rel, meta.ManyToOne) and f.null: if isinstance(f.rel, models.ManyToOne) and f.null:
yield {"text": f.verbose_name} yield {"text": f.verbose_name}
else: else:
th_classes = [] th_classes = []
@ -110,7 +111,7 @@ def items_for_result(cl, result):
row_class = '' row_class = ''
try: try:
f = cl.lookup_opts.get_field(field_name) f = cl.lookup_opts.get_field(field_name)
except meta.FieldDoesNotExist: except models.FieldDoesNotExist:
# For non-field list_display values, the value is a method # For non-field list_display values, the value is a method
# name. Execute the method. # name. Execute the method.
try: try:
@ -126,18 +127,18 @@ def items_for_result(cl, result):
else: else:
field_val = getattr(result, f.attname) field_val = getattr(result, f.attname)
if isinstance(f.rel, meta.ManyToOne): if isinstance(f.rel, models.ManyToOne):
if field_val is not None: if field_val is not None:
result_repr = getattr(result, 'get_%s' % f.name)() result_repr = getattr(result, 'get_%s' % f.name)()
else: else:
result_repr = EMPTY_CHANGELIST_VALUE result_repr = EMPTY_CHANGELIST_VALUE
# Dates and times are special: They're formatted in a certain way. # Dates and times are special: They're formatted in a certain way.
elif isinstance(f, meta.DateField) or isinstance(f, meta.TimeField): elif isinstance(f, models.DateField) or isinstance(f, models.TimeField):
if field_val: if field_val:
(date_format, datetime_format, time_format) = get_date_formats() (date_format, datetime_format, time_format) = get_date_formats()
if isinstance(f, meta.DateTimeField): if isinstance(f, models.DateTimeField):
result_repr = capfirst(dateformat.format(field_val, datetime_format)) result_repr = capfirst(dateformat.format(field_val, datetime_format))
elif isinstance(f, meta.TimeField): elif isinstance(f, models.TimeField):
result_repr = capfirst(dateformat.time_format(field_val, time_format)) result_repr = capfirst(dateformat.time_format(field_val, time_format))
else: else:
result_repr = capfirst(dateformat.format(field_val, date_format)) result_repr = capfirst(dateformat.format(field_val, date_format))
@ -145,15 +146,15 @@ def items_for_result(cl, result):
result_repr = EMPTY_CHANGELIST_VALUE result_repr = EMPTY_CHANGELIST_VALUE
row_class = ' class="nowrap"' row_class = ' class="nowrap"'
# Booleans are special: We use images. # Booleans are special: We use images.
elif isinstance(f, meta.BooleanField) or isinstance(f, meta.NullBooleanField): elif isinstance(f, models.BooleanField) or isinstance(f, models.NullBooleanField):
BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'} BOOLEAN_MAPPING = {True: 'yes', False: 'no', None: 'unknown'}
result_repr = '<img src="%simg/admin/icon-%s.gif" alt="%s" />' % (ADMIN_MEDIA_PREFIX, BOOLEAN_MAPPING[field_val], field_val) result_repr = '<img src="%simg/admin/icon-%s.gif" alt="%s" />' % (ADMIN_MEDIA_PREFIX, BOOLEAN_MAPPING[field_val], field_val)
# ImageFields are special: Use a thumbnail. # ImageFields are special: Use a thumbnail.
elif isinstance(f, meta.ImageField): elif isinstance(f, models.ImageField):
from django.parts.media.photos import get_thumbnail_url from django.parts.media.photos import get_thumbnail_url
result_repr = '<img src="%s" alt="%s" title="%s" />' % (get_thumbnail_url(getattr(result, 'get_%s_url' % f.name)(), '120'), field_val, field_val) result_repr = '<img src="%s" alt="%s" title="%s" />' % (get_thumbnail_url(getattr(result, 'get_%s_url' % f.name)(), '120'), field_val, field_val)
# FloatFields are special: Zero-pad the decimals. # FloatFields are special: Zero-pad the decimals.
elif isinstance(f, meta.FloatField): elif isinstance(f, models.FloatField):
if field_val is not None: if field_val is not None:
result_repr = ('%%.%sf' % f.decimal_places) % field_val result_repr = ('%%.%sf' % f.decimal_places) % field_val
else: else:

View File

@ -3,8 +3,8 @@ from django.utils.html import escape
from django.utils.text import capfirst from django.utils.text import capfirst
from django.utils.functional import curry from django.utils.functional import curry
from django.contrib.admin.views.main import AdminBoundField from django.contrib.admin.views.main import AdminBoundField
from django.core.meta.fields import BoundField, Field from django.db.models.fields import BoundField, Field
from django.core.meta import BoundRelatedObject, TABULAR, STACKED from django.db.models import BoundRelatedObject, TABULAR, STACKED
from django.conf.settings import ADMIN_MEDIA_PREFIX from django.conf.settings import ADMIN_MEDIA_PREFIX
import re import re

View File

@ -7,12 +7,12 @@ class AdminApplistNode(template.Node):
self.varname = varname self.varname = varname
def render(self, context): def render(self, context):
from django.core import meta from django.db import models
from django.utils.text import capfirst from django.utils.text import capfirst
app_list = [] app_list = []
user = context['user'] user = context['user']
for app in meta.get_installed_model_modules(): for app in models.get_installed_model_modules():
app_label = app.__name__[app.__name__.rindex('.')+1:] app_label = app.__name__[app.__name__.rindex('.')+1:]
has_module_perms = user.has_module_perms(app_label) has_module_perms = user.has_module_perms(app_label)

View File

@ -1,12 +1,12 @@
from django.core import meta
from django import templatetags from django import templatetags
from django.conf import settings from django.conf import settings
from django.contrib.admin.views.decorators import staff_member_required from django.contrib.admin.views.decorators import staff_member_required
from django.models.core import sites from django.db import models
from django.core.extensions import DjangoContext, render_to_response from django.core.extensions import DjangoContext, render_to_response
from django.core.exceptions import Http404, ViewDoesNotExist from django.core.exceptions import Http404, ViewDoesNotExist
from django.core import template, urlresolvers from django.core import template, urlresolvers
from django.contrib.admin import utils from django.contrib.admin import utils
from django.models.core import sites
import inspect, os, re import inspect, os, re
# Exclude methods starting with these strings from documentation # Exclude methods starting with these strings from documentation
@ -136,7 +136,7 @@ def model_index(request):
return missing_docutils_page(request) return missing_docutils_page(request)
models = [] models = []
for app in meta.get_installed_model_modules(): for app in models.get_installed_model_modules():
for model in app._MODELS: for model in app._MODELS:
opts = model._meta opts = model._meta
models.append({ models.append({
@ -152,7 +152,7 @@ def model_detail(request, model):
return missing_docutils_page(request) return missing_docutils_page(request)
try: try:
model = meta.get_app(model) model = models.get_app(model)
except ImportError: except ImportError:
raise Http404 raise Http404
opts = model.Klass._meta opts = model.Klass._meta

View File

@ -1,9 +1,9 @@
# Generic admin views. # Generic admin views.
from django.contrib.admin.views.decorators import staff_member_required from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.admin.filterspecs import FilterSpec from django.contrib.admin.filterspecs import FilterSpec
from django.core import formfields, meta, template from django.core import formfields, template
from django.core.template import loader from django.core.template import loader
from django.core.meta.fields import BoundField, BoundFieldLine, BoundFieldSet from django.db.models.fields import BoundField, BoundFieldLine, BoundFieldSet
from django.core.exceptions import Http404, ImproperlyConfigured, ObjectDoesNotExist, PermissionDenied from django.core.exceptions import Http404, ImproperlyConfigured, ObjectDoesNotExist, PermissionDenied
from django.core.extensions import DjangoContext as Context from django.core.extensions import DjangoContext as Context
from django.core.extensions import get_object_or_404, render_to_response from django.core.extensions import get_object_or_404, render_to_response
@ -13,6 +13,7 @@ try:
from django.models.admin import log from django.models.admin import log
except ImportError: except ImportError:
raise ImproperlyConfigured, "You don't have 'django.contrib.admin' in INSTALLED_APPS." raise ImproperlyConfigured, "You don't have 'django.contrib.admin' in INSTALLED_APPS."
from django.db import models
from django.utils.html import strip_tags from django.utils.html import strip_tags
from django.utils.httpwrappers import HttpResponse, HttpResponseRedirect from django.utils.httpwrappers import HttpResponse, HttpResponseRedirect
from django.utils.text import capfirst, get_text_list from django.utils.text import capfirst, get_text_list
@ -40,7 +41,7 @@ EMPTY_CHANGELIST_VALUE = '(None)'
def _get_mod_opts(app_label, module_name): def _get_mod_opts(app_label, module_name):
"Helper function that returns a tuple of (module, opts), raising Http404 if necessary." "Helper function that returns a tuple of (module, opts), raising Http404 if necessary."
try: try:
mod = meta.get_module(app_label, module_name) mod = models.get_module(app_label, module_name)
except ImportError: except ImportError:
raise Http404 # Invalid app or module name. Maybe it's not in INSTALLED_APPS. raise Http404 # Invalid app or module name. Maybe it's not in INSTALLED_APPS.
opts = mod.Klass._meta opts = mod.Klass._meta
@ -161,7 +162,7 @@ class ChangeList(object):
ordering = lookup_opts.admin.ordering or lookup_opts.ordering or ['-' + lookup_opts.pk.name] ordering = lookup_opts.admin.ordering or lookup_opts.ordering or ['-' + lookup_opts.pk.name]
# Normalize it to new-style ordering. # Normalize it to new-style ordering.
ordering = meta.handle_legacy_orderlist(ordering) ordering = models.handle_legacy_orderlist(ordering)
if ordering[0].startswith('-'): if ordering[0].startswith('-'):
order_field, order_type = ordering[0][1:], 'desc' order_field, order_type = ordering[0][1:], 'desc'
@ -171,10 +172,10 @@ class ChangeList(object):
try: try:
try: try:
f = lookup_opts.get_field(lookup_opts.admin.list_display[int(params[ORDER_VAR])]) f = lookup_opts.get_field(lookup_opts.admin.list_display[int(params[ORDER_VAR])])
except meta.FieldDoesNotExist: except models.FieldDoesNotExist:
pass pass
else: else:
if not isinstance(f.rel, meta.ManyToOne) or not f.null: if not isinstance(f.rel, models.ManyToOne) or not f.null:
order_field = f.name order_field = f.name
except (IndexError, ValueError): except (IndexError, ValueError):
pass # Invalid ordering specified. Just use the default. pass # Invalid ordering specified. Just use the default.
@ -196,10 +197,10 @@ class ChangeList(object):
lookup_order_field = order_field lookup_order_field = order_field
try: try:
f = lookup_opts.get_field(order_field) f = lookup_opts.get_field(order_field)
except meta.FieldDoesNotExist: except models.FieldDoesNotExist:
pass pass
else: else:
if isinstance(lookup_opts.get_field(order_field).rel, meta.ManyToOne): if isinstance(lookup_opts.get_field(order_field).rel, models.ManyToOne):
f = lookup_opts.get_field(order_field) f = lookup_opts.get_field(order_field)
rel_ordering = f.rel.to._meta.ordering and f.rel.to._meta.ordering[0] or f.rel.to._meta.pk.column rel_ordering = f.rel.to._meta.ordering and f.rel.to._meta.ordering[0] or f.rel.to._meta.pk.column
lookup_order_field = '%s.%s' % (f.rel.to._meta.db_table, rel_ordering) lookup_order_field = '%s.%s' % (f.rel.to._meta.db_table, rel_ordering)
@ -211,10 +212,10 @@ class ChangeList(object):
for field_name in lookup_opts.admin.list_display: for field_name in lookup_opts.admin.list_display:
try: try:
f = lookup_opts.get_field(field_name) f = lookup_opts.get_field(field_name)
except meta.FieldDoesNotExist: except models.FieldDoesNotExist:
pass pass
else: else:
if isinstance(f.rel, meta.ManyToOne): if isinstance(f.rel, models.ManyToOne):
lookup_params['select_related'] = True lookup_params['select_related'] = True
break break
lookup_params['order_by'] = ((order_type == 'desc' and '-' or '') + lookup_order_field,) lookup_params['order_by'] = ((order_type == 'desc' and '-' or '') + lookup_order_field,)
@ -223,7 +224,7 @@ class ChangeList(object):
for bit in query.split(): for bit in query.split():
or_queries = [] or_queries = []
for field_name in lookup_opts.admin.search_fields: for field_name in lookup_opts.admin.search_fields:
or_queries.append(meta.Q(**{'%s__icontains' % field_name: bit})) or_queries.append(models.Q(**{'%s__icontains' % field_name: bit}))
complex_queries.append(reduce(operator.or_, or_queries)) complex_queries.append(reduce(operator.or_, or_queries))
lookup_params['complex'] = reduce(operator.and_, complex_queries) lookup_params['complex'] = reduce(operator.and_, complex_queries)
if opts.one_to_one_field: if opts.one_to_one_field:
@ -247,14 +248,14 @@ def change_list(request, app_label, module_name):
'admin/change_list'], context_instance=c) 'admin/change_list'], context_instance=c)
change_list = staff_member_required(change_list) change_list = staff_member_required(change_list)
use_raw_id_admin = lambda field: isinstance(field.rel, (meta.ManyToOne, meta.ManyToMany)) and field.rel.raw_id_admin use_raw_id_admin = lambda field: isinstance(field.rel, (models.ManyToOne, models.ManyToMany)) and field.rel.raw_id_admin
def get_javascript_imports(opts,auto_populated_fields, ordered_objects, field_sets): def get_javascript_imports(opts,auto_populated_fields, ordered_objects, field_sets):
# Put in any necessary JavaScript imports. # Put in any necessary JavaScript imports.
js = ['js/core.js', 'js/admin/RelatedObjectLookups.js'] js = ['js/core.js', 'js/admin/RelatedObjectLookups.js']
if auto_populated_fields: if auto_populated_fields:
js.append('js/urlify.js') js.append('js/urlify.js')
if opts.has_field_type(meta.DateTimeField) or opts.has_field_type(meta.TimeField) or opts.has_field_type(meta.DateField): if opts.has_field_type(models.DateTimeField) or opts.has_field_type(models.TimeField) or opts.has_field_type(models.DateField):
js.extend(['js/calendar.js', 'js/admin/DateTimeShortcuts.js']) js.extend(['js/calendar.js', 'js/admin/DateTimeShortcuts.js'])
if ordered_objects: if ordered_objects:
js.extend(['js/getElementsBySelector.js', 'js/dom-drag.js' , 'js/admin/ordering.js']) js.extend(['js/getElementsBySelector.js', 'js/dom-drag.js' , 'js/admin/ordering.js'])
@ -269,7 +270,7 @@ def get_javascript_imports(opts,auto_populated_fields, ordered_objects, field_se
for field_line in field_set: for field_line in field_set:
try: try:
for f in field_line: for f in field_line:
if f.rel and isinstance(f, meta.ManyToManyField) and f.rel.filter_interface: if f.rel and isinstance(f, models.ManyToManyField) and f.rel.filter_interface:
js.extend(['js/SelectBox.js' , 'js/SelectFilter2.js']) js.extend(['js/SelectBox.js' , 'js/SelectFilter2.js'])
raise StopIteration raise StopIteration
except StopIteration: except StopIteration:
@ -281,12 +282,12 @@ class AdminBoundField(BoundField):
super(AdminBoundField, self).__init__(field, field_mapping, original) super(AdminBoundField, self).__init__(field, field_mapping, original)
self.element_id = self.form_fields[0].get_id() self.element_id = self.form_fields[0].get_id()
self.has_label_first = not isinstance(self.field, meta.BooleanField) self.has_label_first = not isinstance(self.field, models.BooleanField)
self.raw_id_admin = use_raw_id_admin(field) self.raw_id_admin = use_raw_id_admin(field)
self.is_date_time = isinstance(field, meta.DateTimeField) self.is_date_time = isinstance(field, models.DateTimeField)
self.is_file_field = isinstance(field, meta.FileField) self.is_file_field = isinstance(field, models.FileField)
self.needs_add_label = field.rel and isinstance(field.rel, meta.ManyToOne) or isinstance(field.rel, meta.ManyToMany) and field.rel.to._meta.admin self.needs_add_label = field.rel and isinstance(field.rel, models.ManyToOne) or isinstance(field.rel, models.ManyToMany) and field.rel.to._meta.admin
self.hidden = isinstance(self.field, meta.AutoField) self.hidden = isinstance(self.field, models.AutoField)
self.first = False self.first = False
classes = [] classes = []
@ -307,10 +308,10 @@ class AdminBoundField(BoundField):
if getattr(self, '_display_filled', False): if getattr(self, '_display_filled', False):
return return
# HACK # HACK
if isinstance(self.field.rel, meta.ManyToOne): if isinstance(self.field.rel, models.ManyToOne):
func_name = 'get_%s' % self.field.name func_name = 'get_%s' % self.field.name
self._display = self._fetch_existing_display(func_name) self._display = self._fetch_existing_display(func_name)
elif isinstance(self.field.rel, meta.ManyToMany): elif isinstance(self.field.rel, models.ManyToMany):
func_name = 'get_%s_list' % self.field.rel.singular func_name = 'get_%s_list' % self.field.rel.singular
self._display = ", ".join([str(obj) for obj in self._fetch_existing_display(func_name)]) self._display = ", ".join([str(obj) for obj in self._fetch_existing_display(func_name)])
self._display_filled = True self._display_filled = True
@ -354,7 +355,7 @@ class AdminBoundManipulator(BoundManipulator):
self.coltype = self.ordered_objects and 'colMS' or 'colM' self.coltype = self.ordered_objects and 'colMS' or 'colM'
self.has_absolute_url = hasattr(opts.get_model_module().Klass, 'get_absolute_url') self.has_absolute_url = hasattr(opts.get_model_module().Klass, 'get_absolute_url')
self.form_enc_attrib = opts.has_field_type(meta.FileField) and \ self.form_enc_attrib = opts.has_field_type(models.FileField) and \
'enctype="multipart/form-data" ' or '' 'enctype="multipart/form-data" ' or ''
self.first_form_field_id = self.bound_field_sets[0].bound_field_lines[0].bound_fields[0].form_fields[0].get_id(); self.first_form_field_id = self.bound_field_sets[0].bound_field_lines[0].bound_fields[0].form_fields[0].get_id();
@ -399,7 +400,7 @@ def add_stage(request, app_label, module_name, show_delete=False, form_url='', p
manipulator = mod.AddManipulator() manipulator = mod.AddManipulator()
if request.POST: if request.POST:
new_data = request.POST.copy() new_data = request.POST.copy()
if opts.has_field_type(meta.FileField): if opts.has_field_type(models.FileField):
new_data.update(request.FILES) new_data.update(request.FILES)
errors = manipulator.get_validation_errors(new_data) errors = manipulator.get_validation_errors(new_data)
manipulator.do_html2python(new_data) manipulator.do_html2python(new_data)
@ -476,7 +477,7 @@ def change_stage(request, app_label, module_name, object_id):
if request.POST: if request.POST:
new_data = request.POST.copy() new_data = request.POST.copy()
if opts.has_field_type(meta.FileField): if opts.has_field_type(models.FileField):
new_data.update(request.FILES) new_data.update(request.FILES)
errors = manipulator.get_validation_errors(new_data) errors = manipulator.get_validation_errors(new_data)
@ -558,7 +559,7 @@ def _get_deleted_objects(deleted_objects, perms_needed, user, obj, opts, current
continue continue
opts_seen.append(related.opts) opts_seen.append(related.opts)
rel_opts_name = related.get_method_name_part() rel_opts_name = related.get_method_name_part()
if isinstance(related.field.rel, meta.OneToOne): if isinstance(related.field.rel, models.OneToOne):
try: try:
sub_obj = getattr(obj, 'get_%s' % rel_opts_name)() sub_obj = getattr(obj, 'get_%s' % rel_opts_name)()
except ObjectDoesNotExist: except ObjectDoesNotExist:

View File

@ -1,31 +1,31 @@
from django.core import meta from django.db import models
from django.models import auth, core from django.models import auth, core
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
class Comment(meta.Model): class Comment(models.Model):
user = meta.ForeignKey(auth.User, raw_id_admin=True) user = models.ForeignKey(auth.User, raw_id_admin=True)
content_type = meta.ForeignKey(core.ContentType) content_type = models.ForeignKey(core.ContentType)
object_id = meta.IntegerField(_('object ID')) object_id = models.IntegerField(_('object ID'))
headline = meta.CharField(_('headline'), maxlength=255, blank=True) headline = models.CharField(_('headline'), maxlength=255, blank=True)
comment = meta.TextField(_('comment'), maxlength=3000) comment = models.TextField(_('comment'), maxlength=3000)
rating1 = meta.PositiveSmallIntegerField(_('rating #1'), blank=True, null=True) rating1 = models.PositiveSmallIntegerField(_('rating #1'), blank=True, null=True)
rating2 = meta.PositiveSmallIntegerField(_('rating #2'), blank=True, null=True) rating2 = models.PositiveSmallIntegerField(_('rating #2'), blank=True, null=True)
rating3 = meta.PositiveSmallIntegerField(_('rating #3'), blank=True, null=True) rating3 = models.PositiveSmallIntegerField(_('rating #3'), blank=True, null=True)
rating4 = meta.PositiveSmallIntegerField(_('rating #4'), blank=True, null=True) rating4 = models.PositiveSmallIntegerField(_('rating #4'), blank=True, null=True)
rating5 = meta.PositiveSmallIntegerField(_('rating #5'), blank=True, null=True) rating5 = models.PositiveSmallIntegerField(_('rating #5'), blank=True, null=True)
rating6 = meta.PositiveSmallIntegerField(_('rating #6'), blank=True, null=True) rating6 = models.PositiveSmallIntegerField(_('rating #6'), blank=True, null=True)
rating7 = meta.PositiveSmallIntegerField(_('rating #7'), blank=True, null=True) rating7 = models.PositiveSmallIntegerField(_('rating #7'), blank=True, null=True)
rating8 = meta.PositiveSmallIntegerField(_('rating #8'), blank=True, null=True) rating8 = models.PositiveSmallIntegerField(_('rating #8'), blank=True, null=True)
# This field designates whether to use this row's ratings in aggregate # This field designates whether to use this row's ratings in aggregate
# functions (summaries). We need this because people are allowed to post # functions (summaries). We need this because people are allowed to post
# multiple reviews on the same thing, but the system will only use the # multiple reviews on the same thing, but the system will only use the
# latest one (with valid_rating=True) in tallying the reviews. # latest one (with valid_rating=True) in tallying the reviews.
valid_rating = meta.BooleanField(_('is valid rating')) valid_rating = models.BooleanField(_('is valid rating'))
submit_date = meta.DateTimeField(_('date/time submitted'), auto_now_add=True) submit_date = models.DateTimeField(_('date/time submitted'), auto_now_add=True)
is_public = meta.BooleanField(_('is public')) is_public = models.BooleanField(_('is public'))
ip_address = meta.IPAddressField(_('IP address'), blank=True, null=True) ip_address = models.IPAddressField(_('IP address'), blank=True, null=True)
is_removed = meta.BooleanField(_('is removed'), help_text=_('Check this box if the comment is inappropriate. A "This comment has been removed" message will be displayed instead.')) is_removed = models.BooleanField(_('is removed'), help_text=_('Check this box if the comment is inappropriate. A "This comment has been removed" message will be displayed instead.'))
site = meta.ForeignKey(core.Site) site = models.ForeignKey(core.Site)
class META: class META:
db_table = 'comments' db_table = 'comments'
verbose_name = _('Comment') verbose_name = _('Comment')
@ -43,7 +43,7 @@ class Comment(meta.Model):
'IS_PUBLIC': 'ip', 'IS_PUBLIC': 'ip',
} }
ordering = ('-submit_date',) ordering = ('-submit_date',)
admin = meta.Admin( admin = models.Admin(
fields = ( fields = (
(None, {'fields': ('content_type', 'object_id', 'site')}), (None, {'fields': ('content_type', 'object_id', 'site')}),
('Content', {'fields': ('user', 'headline', 'comment')}), ('Content', {'fields': ('user', 'headline', 'comment')}),
@ -155,24 +155,24 @@ class Comment(meta.Model):
return True return True
return False return False
class FreeComment(meta.Model): class FreeComment(models.Model):
# A FreeComment is a comment by a non-registered user. # A FreeComment is a comment by a non-registered user.
content_type = meta.ForeignKey(core.ContentType) content_type = models.ForeignKey(core.ContentType)
object_id = meta.IntegerField(_('object ID')) object_id = models.IntegerField(_('object ID'))
comment = meta.TextField(_('comment'), maxlength=3000) comment = models.TextField(_('comment'), maxlength=3000)
person_name = meta.CharField(_("person's name"), maxlength=50) person_name = models.CharField(_("person's name"), maxlength=50)
submit_date = meta.DateTimeField(_('date/time submitted'), auto_now_add=True) submit_date = models.DateTimeField(_('date/time submitted'), auto_now_add=True)
is_public = meta.BooleanField(_('is public')) is_public = models.BooleanField(_('is public'))
ip_address = meta.IPAddressField(_('ip address')) ip_address = models.IPAddressField(_('ip address'))
# TODO: Change this to is_removed, like Comment # TODO: Change this to is_removed, like Comment
approved = meta.BooleanField(_('approved by staff')) approved = models.BooleanField(_('approved by staff'))
site = meta.ForeignKey(core.Site) site = models.ForeignKey(core.Site)
class META: class META:
db_table = 'comments_free' db_table = 'comments_free'
verbose_name = _('Free comment') verbose_name = _('Free comment')
verbose_name_plural = _('Free comments') verbose_name_plural = _('Free comments')
ordering = ('-submit_date',) ordering = ('-submit_date',)
admin = meta.Admin( admin = models.Admin(
fields = ( fields = (
(None, {'fields': ('content_type', 'object_id', 'site')}), (None, {'fields': ('content_type', 'object_id', 'site')}),
('Content', {'fields': ('person_name', 'comment')}), ('Content', {'fields': ('person_name', 'comment')}),
@ -203,11 +203,11 @@ class FreeComment(meta.Model):
get_content_object.short_description = _('Content object') get_content_object.short_description = _('Content object')
class KarmaScore(meta.Model): class KarmaScore(models.Model):
user = meta.ForeignKey(auth.User) user = models.ForeignKey(auth.User)
comment = meta.ForeignKey(Comment) comment = models.ForeignKey(Comment)
score = meta.SmallIntegerField(_('score'), db_index=True) score = models.SmallIntegerField(_('score'), db_index=True)
scored_date = meta.DateTimeField(_('score date'), auto_now=True) scored_date = models.DateTimeField(_('score date'), auto_now=True)
class META: class META:
module_name = 'karma' module_name = 'karma'
verbose_name = _('Karma score') verbose_name = _('Karma score')
@ -242,10 +242,10 @@ class KarmaScore(meta.Model):
return DEFAULT_KARMA return DEFAULT_KARMA
return int(round((4.5 * score) + 5.5)) return int(round((4.5 * score) + 5.5))
class UserFlag(meta.Model): class UserFlag(models.Model):
user = meta.ForeignKey(auth.User) user = models.ForeignKey(auth.User)
comment = meta.ForeignKey(Comment) comment = models.ForeignKey(Comment)
flag_date = meta.DateTimeField(_('flag date'), auto_now_add=True) flag_date = models.DateTimeField(_('flag date'), auto_now_add=True)
class META: class META:
db_table = 'comments_user_flags' db_table = 'comments_user_flags'
verbose_name = _('User flag') verbose_name = _('User flag')
@ -272,10 +272,10 @@ class UserFlag(meta.Model):
mail_managers('Comment flagged', message, fail_silently=True) mail_managers('Comment flagged', message, fail_silently=True)
f.save() f.save()
class ModeratorDeletion(meta.Model): class ModeratorDeletion(models.Model):
user = meta.ForeignKey(auth.User, verbose_name='moderator') user = models.ForeignKey(auth.User, verbose_name='moderator')
comment = meta.ForeignKey(Comment) comment = models.ForeignKey(Comment)
deletion_date = meta.DateTimeField(_('deletion date'), auto_now_add=True) deletion_date = models.DateTimeField(_('deletion date'), auto_now_add=True)
class META: class META:
db_table = 'comments_moderator_deletions' db_table = 'comments_moderator_deletions'
verbose_name = _('Moderator deletion') verbose_name = _('Moderator deletion')

View File

@ -1,23 +1,24 @@
from django.core import meta, validators from django.core validators
from django.db import models
from django.models.core import Site from django.models.core import Site
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
class FlatPage(meta.Model): class FlatPage(models.Model):
url = meta.CharField(_('URL'), maxlength=100, validator_list=[validators.isAlphaNumericURL], url = models.CharField(_('URL'), maxlength=100, validator_list=[validators.isAlphaNumericURL],
help_text=_("Example: '/about/contact/'. Make sure to have leading and trailing slashes.")) help_text=_("Example: '/about/contact/'. Make sure to have leading and trailing slashes."))
title = meta.CharField(_('title'), maxlength=200) title = models.CharField(_('title'), maxlength=200)
content = meta.TextField(_('content')) content = models.TextField(_('content'))
enable_comments = meta.BooleanField(_('enable comments')) enable_comments = models.BooleanField(_('enable comments'))
template_name = meta.CharField(_('template name'), maxlength=70, blank=True, template_name = models.CharField(_('template name'), maxlength=70, blank=True,
help_text=_("Example: 'flatpages/contact_page'. If this isn't provided, the system will use 'flatpages/default'.")) help_text=_("Example: 'flatpages/contact_page'. If this isn't provided, the system will use 'flatpages/default'."))
registration_required = meta.BooleanField(_('registration required'), help_text=_("If this is checked, only logged-in users will be able to view the page.")) registration_required = models.BooleanField(_('registration required'), help_text=_("If this is checked, only logged-in users will be able to view the page."))
sites = meta.ManyToManyField(Site) sites = models.ManyToManyField(Site)
class META: class META:
db_table = 'django_flatpages' db_table = 'django_flatpages'
verbose_name = _('flat page') verbose_name = _('flat page')
verbose_name_plural = _('flat pages') verbose_name_plural = _('flat pages')
ordering = ('url',) ordering = ('url',)
admin = meta.Admin( admin = models.Admin(
fields = ( fields = (
(None, {'fields': ('url', 'title', 'content', 'sites')}), (None, {'fields': ('url', 'title', 'content', 'sites')}),
('Advanced options', {'classes': 'collapse', 'fields': ('enable_comments', 'registration_required', 'template_name')}), ('Advanced options', {'classes': 'collapse', 'fields': ('enable_comments', 'registration_required', 'template_name')}),

View File

@ -1,12 +1,12 @@
from django.core import meta from django.db import models
from django.models.core import Site from django.models.core import Site
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
class Redirect(meta.Model): class Redirect(models.Model):
site = meta.ForeignKey(Site, radio_admin=meta.VERTICAL) site = models.ForeignKey(Site, radio_admin=models.VERTICAL)
old_path = meta.CharField(_('redirect from'), maxlength=200, db_index=True, old_path = models.CharField(_('redirect from'), maxlength=200, db_index=True,
help_text=_("This should be an absolute path, excluding the domain name. Example: '/events/search/'.")) help_text=_("This should be an absolute path, excluding the domain name. Example: '/events/search/'."))
new_path = meta.CharField(_('redirect to'), maxlength=200, blank=True, new_path = models.CharField(_('redirect to'), maxlength=200, blank=True,
help_text=_("This can be either an absolute path (as above) or a full URL starting with 'http://'.")) help_text=_("This can be either an absolute path (as above) or a full URL starting with 'http://'."))
class META: class META:
verbose_name = _('redirect') verbose_name = _('redirect')
@ -14,7 +14,7 @@ class Redirect(meta.Model):
db_table = 'django_redirects' db_table = 'django_redirects'
unique_together=(('site', 'old_path'),) unique_together=(('site', 'old_path'),)
ordering = ('old_path',) ordering = ('old_path',)
admin = meta.Admin( admin = models.Admin(
list_filter = ('site',), list_filter = ('site',),
search_fields = ('old_path', 'new_path'), search_fields = ('old_path', 'new_path'),
) )

View File

@ -60,13 +60,14 @@ get_rel_data_type = lambda f: (f.get_internal_type() == 'AutoField') and 'Intege
def get_sql_create(mod): def get_sql_create(mod):
"Returns a list of the CREATE TABLE SQL statements for the given module." "Returns a list of the CREATE TABLE SQL statements for the given module."
from django.core import db, meta from django.core import db
from django.db import models
final_output = [] final_output = []
for klass in mod._MODELS: for klass in mod._MODELS:
opts = klass._meta opts = klass._meta
table_output = [] table_output = []
for f in opts.fields: for f in opts.fields:
if isinstance(f, meta.ForeignKey): if isinstance(f, models.ForeignKey):
rel_field = f.rel.get_related_field() rel_field = f.rel.get_related_field()
data_type = get_rel_data_type(rel_field) data_type = get_rel_data_type(rel_field)
else: else:
@ -233,11 +234,12 @@ get_sql_initial_data.args = APP_ARGS
def get_sql_sequence_reset(mod): def get_sql_sequence_reset(mod):
"Returns a list of the SQL statements to reset PostgreSQL sequences for the given module." "Returns a list of the SQL statements to reset PostgreSQL sequences for the given module."
from django.core import db, meta from django.core import db
from django.db import models
output = [] output = []
for klass in mod._MODELS: for klass in mod._MODELS:
for f in klass._meta.fields: for f in klass._meta.fields:
if isinstance(f, meta.AutoField): if isinstance(f, models.AutoField):
output.append("SELECT setval('%s_%s_seq', (SELECT max(%s) FROM %s));" % \ output.append("SELECT setval('%s_%s_seq', (SELECT max(%s) FROM %s));" % \
(klass._meta.db_table, f.column, db.db.quote_name(f.column), (klass._meta.db_table, f.column, db.db.quote_name(f.column),
db.db.quote_name(klass._meta.db_table))) db.db.quote_name(klass._meta.db_table)))
@ -368,9 +370,10 @@ get_admin_index.args = APP_ARGS
def init(): def init():
"Initializes the database with auth and core." "Initializes the database with auth and core."
try: try:
from django.core import db, meta from django.core import db
auth = meta.get_app('auth') from django.db import models
core = meta.get_app('core') auth = models.get_app('auth')
core = models.get_app('core')
cursor = db.db.cursor() cursor = db.db.cursor()
for sql in get_sql_create(core) + get_sql_create(auth) + get_sql_initial_data(core) + get_sql_initial_data(auth): for sql in get_sql_create(core) + get_sql_create(auth) + get_sql_initial_data(core) + get_sql_initial_data(auth):
cursor.execute(sql) cursor.execute(sql)
@ -574,10 +577,10 @@ def inspectdb(db_name):
yield "# Also note: You'll have to insert the output of 'django-admin.py sqlinitialdata [appname]'" yield "# Also note: You'll have to insert the output of 'django-admin.py sqlinitialdata [appname]'"
yield "# into your database." yield "# into your database."
yield '' yield ''
yield 'from django.core import meta' yield 'from django.db import models'
yield '' yield ''
for table_name in db.get_table_list(cursor): for table_name in db.get_table_list(cursor):
yield 'class %s(meta.Model):' % table2model(table_name) yield 'class %s(models.Model):' % table2model(table_name)
try: try:
relations = db.get_relations(cursor, table_name) relations = db.get_relations(cursor, table_name)
except NotImplementedError: except NotImplementedError:
@ -588,9 +591,9 @@ def inspectdb(db_name):
rel = relations[i] rel = relations[i]
rel_to = rel[1] == table_name and "'self'" or table2model(rel[1]) rel_to = rel[1] == table_name and "'self'" or table2model(rel[1])
if column_name.endswith('_id'): if column_name.endswith('_id'):
field_desc = '%s = meta.ForeignKey(%s' % (column_name[:-3], rel_to) field_desc = '%s = models.ForeignKey(%s' % (column_name[:-3], rel_to)
else: else:
field_desc = '%s = meta.ForeignKey(%s, db_column=%r' % (column_name, rel_to, column_name) field_desc = '%s = models.ForeignKey(%s, db_column=%r' % (column_name, rel_to, column_name)
else: else:
try: try:
field_type = db.DATA_TYPES_REVERSE[row[1]] field_type = db.DATA_TYPES_REVERSE[row[1]]
@ -610,7 +613,7 @@ def inspectdb(db_name):
if field_type == 'CharField' and row[3]: if field_type == 'CharField' and row[3]:
extra_params['maxlength'] = row[3] extra_params['maxlength'] = row[3]
field_desc = '%s = meta.%s(' % (column_name, field_type) field_desc = '%s = models.%s(' % (column_name, field_type)
field_desc += ', '.join(['%s=%s' % (k, v) for k, v in extra_params.items()]) field_desc += ', '.join(['%s=%s' % (k, v) for k, v in extra_params.items()])
field_desc += ')' field_desc += ')'
if field_type_was_guessed: if field_type_was_guessed:
@ -634,25 +637,25 @@ class ModelErrorCollection:
def get_validation_errors(outfile): def get_validation_errors(outfile):
"Validates all installed models. Writes errors, if any, to outfile. Returns number of errors." "Validates all installed models. Writes errors, if any, to outfile. Returns number of errors."
import django.models import django.models
from django.core import meta from django.db import models
e = ModelErrorCollection(outfile) e = ModelErrorCollection(outfile)
module_list = meta.get_installed_model_modules() module_list = models.get_installed_model_modules()
for module in module_list: for module in module_list:
for mod in module._MODELS: for mod in module._MODELS:
opts = mod._meta opts = mod._meta
# Do field-specific validation. # Do field-specific validation.
for f in opts.fields: for f in opts.fields:
if isinstance(f, meta.CharField) and f.maxlength in (None, 0): if isinstance(f, models.CharField) and f.maxlength in (None, 0):
e.add(opts, '"%s" field: CharFields require a "maxlength" attribute.' % f.name) e.add(opts, '"%s" field: CharFields require a "maxlength" attribute.' % f.name)
if isinstance(f, meta.FloatField): if isinstance(f, models.FloatField):
if f.decimal_places is None: if f.decimal_places is None:
e.add(opts, '"%s" field: FloatFields require a "decimal_places" attribute.' % f.name) e.add(opts, '"%s" field: FloatFields require a "decimal_places" attribute.' % f.name)
if f.max_digits is None: if f.max_digits is None:
e.add(opts, '"%s" field: FloatFields require a "max_digits" attribute.' % f.name) e.add(opts, '"%s" field: FloatFields require a "max_digits" attribute.' % f.name)
if isinstance(f, meta.FileField) and not f.upload_to: if isinstance(f, models.FileField) and not f.upload_to:
e.add(opts, '"%s" field: FileFields require an "upload_to" attribute.' % f.name) e.add(opts, '"%s" field: FileFields require an "upload_to" attribute.' % f.name)
if isinstance(f, meta.ImageField): if isinstance(f, models.ImageField):
try: try:
from PIL import Image from PIL import Image
except ImportError: except ImportError:
@ -676,8 +679,8 @@ def get_validation_errors(outfile):
# Check admin attribute. # Check admin attribute.
if opts.admin is not None: if opts.admin is not None:
if not isinstance(opts.admin, meta.Admin): if not isinstance(opts.admin, models.Admin):
e.add(opts, '"admin" attribute, if given, must be set to a meta.Admin() instance.') e.add(opts, '"admin" attribute, if given, must be set to a models.Admin() instance.')
else: else:
# list_display # list_display
if not isinstance(opts.admin.list_display, (list, tuple)): if not isinstance(opts.admin.list_display, (list, tuple)):
@ -686,12 +689,12 @@ def get_validation_errors(outfile):
for fn in opts.admin.list_display: for fn in opts.admin.list_display:
try: try:
f = opts.get_field(fn) f = opts.get_field(fn)
except meta.FieldDoesNotExist: except models.FieldDoesNotExist:
klass = opts.get_model_module().Klass klass = opts.get_model_module().Klass
if not hasattr(klass, fn) or not callable(getattr(klass, fn)): if not hasattr(klass, fn) or not callable(getattr(klass, fn)):
e.add(opts, '"admin.list_display" refers to %r, which isn\'t a field or method.' % fn) e.add(opts, '"admin.list_display" refers to %r, which isn\'t a field or method.' % fn)
else: else:
if isinstance(f, meta.ManyToManyField): if isinstance(f, models.ManyToManyField):
e.add(opts, '"admin.list_display" doesn\'t support ManyToManyFields (%r).' % fn) e.add(opts, '"admin.list_display" doesn\'t support ManyToManyFields (%r).' % fn)
# list_filter # list_filter
if not isinstance(opts.admin.list_filter, (list, tuple)): if not isinstance(opts.admin.list_filter, (list, tuple)):
@ -700,7 +703,7 @@ def get_validation_errors(outfile):
for fn in opts.admin.list_filter: for fn in opts.admin.list_filter:
try: try:
f = opts.get_field(fn) f = opts.get_field(fn)
except meta.FieldDoesNotExist: except models.FieldDoesNotExist:
e.add(opts, '"admin.list_filter" refers to %r, which isn\'t a field.' % fn) e.add(opts, '"admin.list_filter" refers to %r, which isn\'t a field.' % fn)
# Check ordering attribute. # Check ordering attribute.
@ -713,7 +716,7 @@ def get_validation_errors(outfile):
continue continue
try: try:
opts.get_field(field_name, many_to_many=False) opts.get_field(field_name, many_to_many=False)
except meta.FieldDoesNotExist: except models.FieldDoesNotExist:
e.add(opts, '"ordering" refers to "%s", a field that doesn\'t exist.' % field_name) e.add(opts, '"ordering" refers to "%s", a field that doesn\'t exist.' % field_name)
# Check core=True, if needed. # Check core=True, if needed.
@ -731,10 +734,10 @@ def get_validation_errors(outfile):
for field_name in ut: for field_name in ut:
try: try:
f = opts.get_field(field_name, many_to_many=True) f = opts.get_field(field_name, many_to_many=True)
except meta.FieldDoesNotExist: except models.FieldDoesNotExist:
e.add(opts, '"unique_together" refers to %s, a field that doesn\'t exist. Check your syntax.' % field_name) e.add(opts, '"unique_together" refers to %s, a field that doesn\'t exist. Check your syntax.' % field_name)
else: else:
if isinstance(f.rel, meta.ManyToMany): if isinstance(f.rel, models.ManyToMany):
e.add(opts, '"unique_together" refers to %s. ManyToManyFields are not supported in unique_together.' % f.name) e.add(opts, '"unique_together" refers to %s. ManyToManyFields are not supported in unique_together.' % f.name)
return len(e.errors) return len(e.errors)
@ -783,12 +786,13 @@ runserver.args = '[optional port number, or ipaddr:port]'
def createcachetable(tablename): def createcachetable(tablename):
"Creates the table needed to use the SQL cache backend" "Creates the table needed to use the SQL cache backend"
from django.core import db, meta from django.core import db
from django.db import models
fields = ( fields = (
# "key" is a reserved word in MySQL, so use "cache_key" instead. # "key" is a reserved word in MySQL, so use "cache_key" instead.
meta.CharField(name='cache_key', maxlength=255, unique=True, primary_key=True), models.CharField(name='cache_key', maxlength=255, unique=True, primary_key=True),
meta.TextField(name='value'), models.TextField(name='value'),
meta.DateTimeField(name='expires', db_index=True), models.DateTimeField(name='expires', db_index=True),
) )
table_output = [] table_output = []
index_output = [] index_output = []
@ -943,12 +947,12 @@ def execute_from_command_line(action_mapping=DEFAULT_ACTION_MAPPING):
addr, port = '', args[1] addr, port = '', args[1]
action_mapping[action](addr, port) action_mapping[action](addr, port)
else: else:
from django.core import meta from django.db import models
if action == 'dbcheck': if action == 'dbcheck':
mod_list = meta.get_all_installed_modules() mod_list = models.get_all_installed_modules()
else: else:
try: try:
mod_list = [meta.get_app(app_label) for app_label in args[1:]] mod_list = [models.get_app(app_label) for app_label in args[1:]]
except ImportError, e: except ImportError, e:
sys.stderr.write("Error: %s. Are you sure your INSTALLED_APPS setting is correct?\n" % e) sys.stderr.write("Error: %s. Are you sure your INSTALLED_APPS setting is correct?\n" % e)
sys.exit(1) sys.exit(1)

0
django/db/__init__.py Normal file
View File

View File

@ -2,7 +2,7 @@ from django.conf import settings
from django.core import formfields, validators from django.core import formfields, validators
from django.core import db from django.core import db
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.core.meta.fields import * from django.db.models.fields import *
from django.utils.functional import curry from django.utils.functional import curry
from django.utils.text import capfirst from django.utils.text import capfirst
import copy, datetime, os, re, sys, types import copy, datetime, os, re, sys, types

View File

@ -1,11 +1,12 @@
from django.core import meta, validators from django.core import validators
from django.db import models
from django.models import core from django.models import core
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
class Permission(meta.Model): class Permission(models.Model):
name = meta.CharField(_('name'), maxlength=50) name = models.CharField(_('name'), maxlength=50)
package = meta.ForeignKey(core.Package, db_column='package') package = models.ForeignKey(core.Package, db_column='package')
codename = meta.CharField(_('codename'), maxlength=100) codename = models.CharField(_('codename'), maxlength=100)
class META: class META:
verbose_name = _('Permission') verbose_name = _('Permission')
verbose_name_plural = _('Permissions') verbose_name_plural = _('Permissions')
@ -15,34 +16,34 @@ class Permission(meta.Model):
def __repr__(self): def __repr__(self):
return "%s | %s" % (self.package_id, self.name) return "%s | %s" % (self.package_id, self.name)
class Group(meta.Model): class Group(models.Model):
name = meta.CharField(_('name'), maxlength=80, unique=True) name = models.CharField(_('name'), maxlength=80, unique=True)
permissions = meta.ManyToManyField(Permission, blank=True, filter_interface=meta.HORIZONTAL) permissions = models.ManyToManyField(Permission, blank=True, filter_interface=models.HORIZONTAL)
class META: class META:
verbose_name = _('Group') verbose_name = _('Group')
verbose_name_plural = _('Groups') verbose_name_plural = _('Groups')
ordering = ('name',) ordering = ('name',)
admin = meta.Admin( admin = models.Admin(
search_fields = ('name',), search_fields = ('name',),
) )
def __repr__(self): def __repr__(self):
return self.name return self.name
class User(meta.Model): class User(models.Model):
username = meta.CharField(_('username'), maxlength=30, unique=True, validator_list=[validators.isAlphaNumeric]) username = models.CharField(_('username'), maxlength=30, unique=True, validator_list=[validators.isAlphaNumeric])
first_name = meta.CharField(_('first name'), maxlength=30, blank=True) first_name = models.CharField(_('first name'), maxlength=30, blank=True)
last_name = meta.CharField(_('last name'), maxlength=30, blank=True) last_name = models.CharField(_('last name'), maxlength=30, blank=True)
email = meta.EmailField(_('e-mail address'), blank=True) email = models.EmailField(_('e-mail address'), blank=True)
password = meta.CharField(_('password'), maxlength=128, help_text=_("Use '[algo]$[salt]$[hexdigest]'")) password = models.CharField(_('password'), maxlength=128, help_text=_("Use '[algo]$[salt]$[hexdigest]'"))
is_staff = meta.BooleanField(_('staff status'), help_text=_("Designates whether the user can log into this admin site.")) is_staff = models.BooleanField(_('staff status'), help_text=_("Designates whether the user can log into this admin site."))
is_active = meta.BooleanField(_('active'), default=True) is_active = models.BooleanField(_('active'), default=True)
is_superuser = meta.BooleanField(_('superuser status')) is_superuser = models.BooleanField(_('superuser status'))
last_login = meta.DateTimeField(_('last login'), default=meta.LazyDate()) last_login = models.DateTimeField(_('last login'), default=models.LazyDate())
date_joined = meta.DateTimeField(_('date joined'), default=meta.LazyDate()) date_joined = models.DateTimeField(_('date joined'), default=models.LazyDate())
groups = meta.ManyToManyField(Group, blank=True, groups = models.ManyToManyField(Group, blank=True,
help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in.")) help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in."))
user_permissions = meta.ManyToManyField(Permission, blank=True, filter_interface=meta.HORIZONTAL) user_permissions = models.ManyToManyField(Permission, blank=True, filter_interface=models.HORIZONTAL)
class META: class META:
verbose_name = _('User') verbose_name = _('User')
verbose_name_plural = _('Users') verbose_name_plural = _('Users')
@ -51,7 +52,7 @@ class User(meta.Model):
} }
ordering = ('username',) ordering = ('username',)
exceptions = ('SiteProfileNotAvailable',) exceptions = ('SiteProfileNotAvailable',)
admin = meta.Admin( admin = models.Admin(
fields = ( fields = (
(None, {'fields': ('username', 'password')}), (None, {'fields': ('username', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
@ -211,9 +212,9 @@ class User(meta.Model):
from random import choice from random import choice
return ''.join([choice(allowed_chars) for i in range(length)]) return ''.join([choice(allowed_chars) for i in range(length)])
class Message(meta.Model): class Message(models.Model):
user = meta.ForeignKey(User) user = models.ForeignKey(User)
message = meta.TextField(_('Message')) message = models.TextField(_('Message'))
def __repr__(self): def __repr__(self):
return self.message return self.message

View File

@ -1,17 +1,17 @@
import base64, md5, random, sys import base64, md5, random, sys
import cPickle as pickle import cPickle as pickle
from django.core import meta from django.db import models
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
class Site(meta.Model): class Site(models.Model):
domain = meta.CharField(_('domain name'), maxlength=100) domain = models.CharField(_('domain name'), maxlength=100)
name = meta.CharField(_('display name'), maxlength=50) name = models.CharField(_('display name'), maxlength=50)
class META: class META:
verbose_name = _('site') verbose_name = _('site')
verbose_name_plural = _('sites') verbose_name_plural = _('sites')
db_table = 'sites' db_table = 'sites'
ordering = ('domain',) ordering = ('domain',)
admin = meta.Admin( admin = models.Admin(
list_display = ('domain', 'name'), list_display = ('domain', 'name'),
search_fields = ('domain', 'name'), search_fields = ('domain', 'name'),
) )
@ -24,9 +24,9 @@ class Site(meta.Model):
from django.conf.settings import SITE_ID from django.conf.settings import SITE_ID
return get_object(pk=SITE_ID) return get_object(pk=SITE_ID)
class Package(meta.Model): class Package(models.Model):
label = meta.CharField(_('label'), maxlength=20, primary_key=True) label = models.CharField(_('label'), maxlength=20, primary_key=True)
name = meta.CharField(_('name'), maxlength=30, unique=True) name = models.CharField(_('name'), maxlength=30, unique=True)
class META: class META:
verbose_name = _('package') verbose_name = _('package')
verbose_name_plural = _('packages') verbose_name_plural = _('packages')
@ -36,10 +36,10 @@ class Package(meta.Model):
def __repr__(self): def __repr__(self):
return self.name return self.name
class ContentType(meta.Model): class ContentType(models.Model):
name = meta.CharField(_('name'), maxlength=100) name = models.CharField(_('name'), maxlength=100)
package = meta.ForeignKey(Package, db_column='package') package = models.ForeignKey(Package, db_column='package')
python_module_name = meta.CharField(_('python module name'), maxlength=50) python_module_name = models.CharField(_('python module name'), maxlength=50)
class META: class META:
verbose_name = _('content type') verbose_name = _('content type')
verbose_name_plural = _('content types') verbose_name_plural = _('content types')
@ -63,10 +63,10 @@ class ContentType(meta.Model):
""" """
return self.get_model_module().get_object(**kwargs) return self.get_model_module().get_object(**kwargs)
class Session(meta.Model): class Session(models.Model):
session_key = meta.CharField(_('session key'), maxlength=40, primary_key=True) session_key = models.CharField(_('session key'), maxlength=40, primary_key=True)
session_data = meta.TextField(_('session data')) session_data = models.TextField(_('session data'))
expire_date = meta.DateTimeField(_('expire date')) expire_date = models.DateTimeField(_('expire date'))
class META: class META:
verbose_name = _('session') verbose_name = _('session')
verbose_name_plural = _('sessions') verbose_name_plural = _('sessions')

View File

@ -4,11 +4,11 @@
This is a basic model with only two non-primary-key fields. This is a basic model with only two non-primary-key fields.
""" """
from django.core import meta from django.db import models
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=100, default='Default headline') headline = models.CharField(maxlength=100, default='Default headline')
pub_date = meta.DateTimeField() pub_date = models.DateTimeField()
API_TESTS = """ API_TESTS = """
# No articles are in the system yet. # No articles are in the system yet.

View File

@ -9,16 +9,16 @@ For each field that has ``choices``, a model instance gets a
field. This method returns the "human-readable" value of the field. field. This method returns the "human-readable" value of the field.
""" """
from django.core import meta from django.db import models
GENDER_CHOICES = ( GENDER_CHOICES = (
('M', 'Male'), ('M', 'Male'),
('F', 'Female'), ('F', 'Female'),
) )
class Person(meta.Model): class Person(models.Model):
name = meta.CharField(maxlength=20) name = models.CharField(maxlength=20)
gender = meta.CharField(maxlength=1, choices=GENDER_CHOICES) gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
def __repr__(self): def __repr__(self):
return self.name return self.name

View File

@ -6,11 +6,11 @@ If your database column name is different than your model attribute, use the
name, in API usage. name, in API usage.
""" """
from django.core import meta from django.db import models
class Person(meta.Model): class Person(models.Model):
first_name = meta.CharField(maxlength=30, db_column='firstname') first_name = models.CharField(maxlength=30, db_column='firstname')
last_name = meta.CharField(maxlength=30, db_column='last') last_name = models.CharField(maxlength=30, db_column='last')
def __repr__(self): def __repr__(self):
return '%s %s' % (self.first_name, self.last_name) return '%s %s' % (self.first_name, self.last_name)

View File

@ -4,11 +4,11 @@
Any method you add to a model will be available to instances. Any method you add to a model will be available to instances.
""" """
from django.core import meta from django.db import models
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=100) headline = models.CharField(maxlength=100)
pub_date = meta.DateField() pub_date = models.DateField()
def __repr__(self): def __repr__(self):
return self.headline return self.headline

View File

@ -5,21 +5,21 @@ By default, Django adds an ``"id"`` field to each model. But you can override
this behavior by explicitly adding ``primary_key=True`` to a field. this behavior by explicitly adding ``primary_key=True`` to a field.
""" """
from django.core import meta from django.db import models
class Employee(meta.Model): class Employee(models.Model):
employee_code = meta.CharField(maxlength=10, primary_key=True) employee_code = models.CharField(maxlength=10, primary_key=True)
first_name = meta.CharField(maxlength=20) first_name = models.CharField(maxlength=20)
last_name = meta.CharField(maxlength=20) last_name = models.CharField(maxlength=20)
class META: class META:
ordering = ('last_name', 'first_name') ordering = ('last_name', 'first_name')
def __repr__(self): def __repr__(self):
return "%s %s" % (self.first_name, self.last_name) return "%s %s" % (self.first_name, self.last_name)
class Business(meta.Model): class Business(models.Model):
name = meta.CharField(maxlength=20, primary_key=True) name = models.CharField(maxlength=20, primary_key=True)
employees = meta.ManyToManyField(Employee) employees = models.ManyToManyField(Employee)
class META: class META:
verbose_name_plural = 'businesses' verbose_name_plural = 'businesses'
module_name = 'businesses' module_name = 'businesses'

View File

@ -8,11 +8,11 @@ object in the database according to that field. "Latest" means "having the
date farthest into the future." date farthest into the future."
""" """
from django.core import meta from django.db import models
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=100) headline = models.CharField(maxlength=100)
pub_date = meta.DateTimeField() pub_date = models.DateTimeField()
class META: class META:
get_latest_by = 'pub_date' get_latest_by = 'pub_date'

View File

@ -4,11 +4,11 @@
This demonstrates features of the database API. This demonstrates features of the database API.
""" """
from django.core import meta from django.db import models
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=100) headline = models.CharField(maxlength=100)
pub_date = meta.DateTimeField() pub_date = models.DateTimeField()
class META: class META:
ordering = ('-pub_date', 'headline') ordering = ('-pub_date', 'headline')

View File

@ -10,26 +10,26 @@ which specifies the ``Reporter``'s position for the given article (e.g. "Staff
writer"). writer").
""" """
from django.core import meta from django.db import models
class Reporter(meta.Model): class Reporter(models.Model):
first_name = meta.CharField(maxlength=30) first_name = models.CharField(maxlength=30)
last_name = meta.CharField(maxlength=30) last_name = models.CharField(maxlength=30)
def __repr__(self): def __repr__(self):
return "%s %s" % (self.first_name, self.last_name) return "%s %s" % (self.first_name, self.last_name)
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=100) headline = models.CharField(maxlength=100)
pub_date = meta.DateField() pub_date = models.DateField()
def __repr__(self): def __repr__(self):
return self.headline return self.headline
class Writer(meta.Model): class Writer(models.Model):
reporter = meta.ForeignKey(Reporter) reporter = models.ForeignKey(Reporter)
article = meta.ForeignKey(Article) article = models.ForeignKey(Article)
position = meta.CharField(maxlength=100) position = models.CharField(maxlength=100)
def __repr__(self): def __repr__(self):
return '%r (%s)' % (self.get_reporter(), self.position) return '%r (%s)' % (self.get_reporter(), self.position)

View File

@ -10,22 +10,22 @@ Set ``singular`` to designate what the category object is called. This is
required if a model has multiple ``ManyToManyFields`` to the same object. required if a model has multiple ``ManyToManyFields`` to the same object.
""" """
from django.core import meta from django.db import models
class Category(meta.Model): class Category(models.Model):
name = meta.CharField(maxlength=20) name = models.CharField(maxlength=20)
class META: class META:
ordering = ('name',) ordering = ('name',)
def __repr__(self): def __repr__(self):
return self.name return self.name
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=50) headline = models.CharField(maxlength=50)
pub_date = meta.DateTimeField() pub_date = models.DateTimeField()
primary_categories = meta.ManyToManyField(Category, primary_categories = models.ManyToManyField(Category,
singular='primary_category', related_name='primary_article') singular='primary_category', related_name='primary_article')
secondary_categories = meta.ManyToManyField(Category, secondary_categories = models.ManyToManyField(Category,
singular='secondary_category', related_name='secondary_article') singular='secondary_category', related_name='secondary_article')
class META: class META:
ordering = ('pub_date',) ordering = ('pub_date',)

View File

@ -10,11 +10,11 @@ In this example, a ``Category`` is related to itself. That is, each
Set ``related_name`` to designate what the reverse relationship is called. Set ``related_name`` to designate what the reverse relationship is called.
""" """
from django.core import meta from django.db import models
class Category(meta.Model): class Category(models.Model):
name = meta.CharField(maxlength=20) name = models.CharField(maxlength=20)
parent = meta.ForeignKey('self', null=True, related_name='child') parent = models.ForeignKey('self', null=True, related_name='child')
def __repr__(self): def __repr__(self):
return self.name return self.name

View File

@ -7,12 +7,12 @@ which are other ``Person`` objects.
Set ``related_name`` to designate what the reverse relationship is called. Set ``related_name`` to designate what the reverse relationship is called.
""" """
from django.core import meta from django.db import models
class Person(meta.Model): class Person(models.Model):
full_name = meta.CharField(maxlength=20) full_name = models.CharField(maxlength=20)
mother = meta.ForeignKey('self', null=True, related_name='mothers_child') mother = models.ForeignKey('self', null=True, related_name='mothers_child')
father = meta.ForeignKey('self', null=True, related_name='fathers_child') father = models.ForeignKey('self', null=True, related_name='fathers_child')
def __repr__(self): def __repr__(self):
return self.full_name return self.full_name

View File

@ -7,17 +7,17 @@ In this example, an article can be published in multiple publications,
and a publication has multiple articles. and a publication has multiple articles.
""" """
from django.core import meta from django.db import models
class Publication(meta.Model): class Publication(models.Model):
title = meta.CharField(maxlength=30) title = models.CharField(maxlength=30)
def __repr__(self): def __repr__(self):
return self.title return self.title
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=100) headline = models.CharField(maxlength=100)
publications = meta.ManyToManyField(Publication) publications = models.ManyToManyField(Publication)
def __repr__(self): def __repr__(self):
return self.headline return self.headline

View File

@ -4,20 +4,20 @@
To define a many-to-one relationship, use ``ForeignKey()`` . To define a many-to-one relationship, use ``ForeignKey()`` .
""" """
from django.core import meta from django.db import models
class Reporter(meta.Model): class Reporter(models.Model):
first_name = meta.CharField(maxlength=30) first_name = models.CharField(maxlength=30)
last_name = meta.CharField(maxlength=30) last_name = models.CharField(maxlength=30)
email = meta.EmailField() email = models.EmailField()
def __repr__(self): def __repr__(self):
return "%s %s" % (self.first_name, self.last_name) return "%s %s" % (self.first_name, self.last_name)
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=100) headline = models.CharField(maxlength=100)
pub_date = meta.DateField() pub_date = models.DateField()
reporter = meta.ForeignKey(Reporter) reporter = models.ForeignKey(Reporter)
def __repr__(self): def __repr__(self):
return self.headline return self.headline

View File

@ -5,17 +5,17 @@ To define a many-to-one relationship that can have a null foreign key, use
``ForeignKey()`` with ``null=True`` . ``ForeignKey()`` with ``null=True`` .
""" """
from django.core import meta from django.db import models
class Reporter(meta.Model): class Reporter(models.Model):
name = meta.CharField(maxlength=30) name = models.CharField(maxlength=30)
def __repr__(self): def __repr__(self):
return self.name return self.name
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=100) headline = models.CharField(maxlength=100)
reporter = meta.ForeignKey(Reporter, null=True) reporter = models.ForeignKey(Reporter, null=True)
def __repr__(self): def __repr__(self):
return self.headline return self.headline

View File

@ -6,26 +6,26 @@ To define a one-to-one relationship, use ``OneToOneField()``.
In this example, a ``Place`` optionally can be a ``Restaurant``. In this example, a ``Place`` optionally can be a ``Restaurant``.
""" """
from django.core import meta from django.db import models
class Place(meta.Model): class Place(models.Model):
name = meta.CharField(maxlength=50) name = models.CharField(maxlength=50)
address = meta.CharField(maxlength=80) address = models.CharField(maxlength=80)
def __repr__(self): def __repr__(self):
return "%s the place" % self.name return "%s the place" % self.name
class Restaurant(meta.Model): class Restaurant(models.Model):
place = meta.OneToOneField(Place) place = models.OneToOneField(Place)
serves_hot_dogs = meta.BooleanField() serves_hot_dogs = models.BooleanField()
serves_pizza = meta.BooleanField() serves_pizza = models.BooleanField()
def __repr__(self): def __repr__(self):
return "%s the restaurant" % self.get_place().name return "%s the restaurant" % self.get_place().name
class Waiter(meta.Model): class Waiter(models.Model):
restaurant = meta.ForeignKey(Restaurant) restaurant = models.ForeignKey(Restaurant)
name = meta.CharField(maxlength=50) name = models.CharField(maxlength=50)
def __repr__(self): def __repr__(self):
return "%s the waiter at %r" % (self.name, self.get_restaurant()) return "%s the waiter at %r" % (self.name, self.get_restaurant())

View File

@ -3,14 +3,14 @@
To perform an OR lookup, or a lookup that combines ANDs and ORs, use the To perform an OR lookup, or a lookup that combines ANDs and ORs, use the
``complex`` keyword argument, and pass it an expression of clauses using the ``complex`` keyword argument, and pass it an expression of clauses using the
variable ``django.core.meta.Q``. variable ``django.db.models.Q``.
""" """
from django.core import meta from django.db import models
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=50) headline = models.CharField(maxlength=50)
pub_date = meta.DateTimeField() pub_date = models.DateTimeField()
class META: class META:
ordering = ('pub_date',) ordering = ('pub_date',)
@ -19,7 +19,7 @@ class Article(meta.Model):
API_TESTS = """ API_TESTS = """
>>> from datetime import datetime >>> from datetime import datetime
>>> from django.core.meta import Q >>> from django.db.models import Q
>>> a1 = Article(headline='Hello', pub_date=datetime(2005, 11, 27)) >>> a1 = Article(headline='Hello', pub_date=datetime(2005, 11, 27))
>>> a1.save() >>> a1.save()

View File

@ -13,11 +13,11 @@ The ordering attribute is not required. If you leave it off, ordering will be
undefined -- not random, just undefined. undefined -- not random, just undefined.
""" """
from django.core import meta from django.db import models
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=100) headline = models.CharField(maxlength=100)
pub_date = meta.DateTimeField() pub_date = models.DateTimeField()
class META: class META:
ordering = ('-pub_date', 'headline') ordering = ('-pub_date', 'headline')

View File

@ -2,11 +2,11 @@
22. Using properties on models 22. Using properties on models
""" """
from django.core import meta from django.db import models
class Person(meta.Model): class Person(models.Model):
first_name = meta.CharField(maxlength=30) first_name = models.CharField(maxlength=30)
last_name = meta.CharField(maxlength=30) last_name = models.CharField(maxlength=30)
def _get_full_name(self): def _get_full_name(self):
return "%s %s" % (self.first_name, self.last_name) return "%s %s" % (self.first_name, self.last_name)

View File

@ -8,11 +8,11 @@ because objects' representations are used throughout Django's
automatically-generated admin. automatically-generated admin.
""" """
from django.core import meta from django.db import models
class Article(meta.Model): class Article(models.Model):
headline = meta.CharField(maxlength=100) headline = models.CharField(maxlength=100)
pub_date = meta.DateTimeField() pub_date = models.DateTimeField()
def __repr__(self): def __repr__(self):
return self.headline return self.headline

View File

@ -7,17 +7,17 @@ appropriately behind the scenes, so your database won't complain about
reserved-name usage. reserved-name usage.
""" """
from django.core import meta from django.db import models
class Thing(meta.Model): class Thing(models.Model):
when = meta.CharField(maxlength=1, primary_key=True) when = models.CharField(maxlength=1, primary_key=True)
join = meta.CharField(maxlength=1) join = models.CharField(maxlength=1)
like = meta.CharField(maxlength=1) like = models.CharField(maxlength=1)
drop = meta.CharField(maxlength=1) drop = models.CharField(maxlength=1)
alter = meta.CharField(maxlength=1) alter = models.CharField(maxlength=1)
having = meta.CharField(maxlength=1) having = models.CharField(maxlength=1)
where = meta.CharField(maxlength=1) where = models.CharField(maxlength=1)
has_hyphen = meta.CharField(maxlength=1, db_column='has-hyphen') has_hyphen = models.CharField(maxlength=1, db_column='has-hyphen')
class META: class META:
db_table = 'select' db_table = 'select'

View File

@ -10,11 +10,11 @@ Django provides hooks for executing arbitrary code around ``save()`` and
* ``_post_delete()`` is called after an object is deleted. * ``_post_delete()`` is called after an object is deleted.
""" """
from django.core import meta from django.db import models
class Person(meta.Model): class Person(models.Model):
first_name = meta.CharField(maxlength=20) first_name = models.CharField(maxlength=20)
last_name = meta.CharField(maxlength=20) last_name = models.CharField(maxlength=20)
def __repr__(self): def __repr__(self):
return "%s %s" % (self.first_name, self.last_name) return "%s %s" % (self.first_name, self.last_name)

View File

@ -5,7 +5,7 @@ You can subclass another model to create a copy of it that behaves slightly
differently. differently.
""" """
from django.core import meta from django.db import models
# From the "Bare-bones model" example # From the "Bare-bones model" example
from modeltests.basic.models import Article from modeltests.basic.models import Article
@ -19,7 +19,7 @@ from modeltests.ordering.models import Article as ArticleWithOrdering
# This uses all fields and metadata from Article and # This uses all fields and metadata from Article and
# adds a "section" field. # adds a "section" field.
class ArticleWithSection(Article): class ArticleWithSection(Article):
section = meta.CharField(maxlength=30) section = models.CharField(maxlength=30)
# This uses all fields and metadata from Article but # This uses all fields and metadata from Article but
# removes the "pub_date" field. # removes the "pub_date" field.
@ -30,15 +30,15 @@ class ArticleWithoutPubDate(Article):
# This uses all fields and metadata from Article but # This uses all fields and metadata from Article but
# overrides the "pub_date" field. # overrides the "pub_date" field.
class ArticleWithFieldOverride(Article): class ArticleWithFieldOverride(Article):
pub_date = meta.DateField() # overrides the old field, a DateTimeField pub_date = models.DateField() # overrides the old field, a DateTimeField
# No need to add remove_fields = ('pub_date',) # No need to add remove_fields = ('pub_date',)
# This uses all fields and metadata from ArticleWithRepr and # This uses all fields and metadata from ArticleWithRepr and
# makes a few additions/changes. # makes a few additions/changes.
class ArticleWithManyChanges(ArticleWithRepr): class ArticleWithManyChanges(ArticleWithRepr):
section = meta.CharField(maxlength=30) section = models.CharField(maxlength=30)
is_popular = meta.BooleanField() is_popular = models.BooleanField()
pub_date = meta.DateField() # overrides the old field, a DateTimeField pub_date = models.DateField() # overrides the old field, a DateTimeField
# This uses all fields from ArticleWithOrdering but # This uses all fields from ArticleWithOrdering but
# changes the ordering parameter. # changes the ordering parameter.
@ -47,10 +47,10 @@ class ArticleWithChangedMeta(ArticleWithOrdering):
ordering = ('headline', 'pub_date') ordering = ('headline', 'pub_date')
class NoModuleNameFirst(Article): class NoModuleNameFirst(Article):
section = meta.CharField(maxlength=30) section = models.CharField(maxlength=30)
class NoModuleNameSecond(Article): class NoModuleNameSecond(Article):
section = meta.CharField(maxlength=30) section = models.CharField(maxlength=30)
API_TESTS = """ API_TESTS = """
# No data is in the system yet. # No data is in the system yet.