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.

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.
"""
from django.core import meta
from django.db import models
import datetime
class FilterSpec(object):
@ -50,7 +50,7 @@ class FilterSpec(object):
class RelatedFilterSpec(FilterSpec):
def __init__(self, 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
else:
self.lookup_title = f.verbose_name
@ -103,7 +103,7 @@ class DateFieldFilterSpec(FilterSpec):
today = datetime.date.today()
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 = (
(_('Any date'), {}),
@ -126,7 +126,7 @@ class DateFieldFilterSpec(FilterSpec):
'query_string': cl.get_query_string( param_dict, self.field_generic),
'display': title}
FilterSpec.register(lambda f: isinstance(f, meta.DateField), DateFieldFilterSpec)
FilterSpec.register(lambda f: isinstance(f, models.DateField), DateFieldFilterSpec)
class BooleanFieldFilterSpec(FilterSpec):
def __init__(self, f, request, params):
@ -144,9 +144,9 @@ class BooleanFieldFilterSpec(FilterSpec):
yield {'selected': self.lookup_val == v and not self.lookup_val2,
'query_string': cl.get_query_string( {self.lookup_kwarg: v}, [self.lookup_kwarg2]),
'display': k}
if isinstance(self.field, meta.NullBooleanField):
if isinstance(self.field, models.NullBooleanField):
yield {'selected': self.lookup_val2 == 'True',
'query_string': cl.get_query_string( {self.lookup_kwarg2: 'True'}, [self.lookup_kwarg]),
'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.utils.translation import gettext_lazy as _
class LogEntry(meta.Model):
action_time = meta.DateTimeField(_('action time'), auto_now=True)
user = meta.ForeignKey(auth.User)
content_type = meta.ForeignKey(core.ContentType, blank=True, null=True)
object_id = meta.TextField(_('object id'), blank=True, null=True)
object_repr = meta.CharField(_('object repr'), maxlength=200)
action_flag = meta.PositiveSmallIntegerField(_('action flag'))
change_message = meta.TextField(_('change message'), blank=True)
class LogEntry(models.Model):
action_time = models.DateTimeField(_('action time'), auto_now=True)
user = models.ForeignKey(auth.User)
content_type = models.ForeignKey(core.ContentType, blank=True, null=True)
object_id = models.TextField(_('object id'), blank=True, null=True)
object_repr = models.CharField(_('object repr'), maxlength=200)
action_flag = models.PositiveSmallIntegerField(_('action flag'))
change_message = models.TextField(_('change message'), blank=True)
class META:
module_name = 'log'
verbose_name = _('log entry')
verbose_name_plural = _('log entries')
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 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.core import meta, template
from django.core import template
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.utils import dateformat
from django.utils.html import strip_tags, escape
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):
try:
f = lookup_opts.get_field(field_name)
except meta.FieldDoesNotExist:
except models.FieldDoesNotExist:
# For non-field list_display values, check for the function
# attribute "short_description". If that doesn't exist, fall
# 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.
yield {"text": header}
else:
if isinstance(f.rel, meta.ManyToOne) and f.null:
if isinstance(f.rel, models.ManyToOne) and f.null:
yield {"text": f.verbose_name}
else:
th_classes = []
@ -110,7 +111,7 @@ def items_for_result(cl, result):
row_class = ''
try:
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
# name. Execute the method.
try:
@ -126,18 +127,18 @@ def items_for_result(cl, result):
else:
field_val = getattr(result, f.attname)
if isinstance(f.rel, meta.ManyToOne):
if isinstance(f.rel, models.ManyToOne):
if field_val is not None:
result_repr = getattr(result, 'get_%s' % f.name)()
else:
result_repr = EMPTY_CHANGELIST_VALUE
# 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:
(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))
elif isinstance(f, meta.TimeField):
elif isinstance(f, models.TimeField):
result_repr = capfirst(dateformat.time_format(field_val, time_format))
else:
result_repr = capfirst(dateformat.format(field_val, date_format))
@ -145,15 +146,15 @@ def items_for_result(cl, result):
result_repr = EMPTY_CHANGELIST_VALUE
row_class = ' class="nowrap"'
# 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'}
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.
elif isinstance(f, meta.ImageField):
elif isinstance(f, models.ImageField):
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)
# FloatFields are special: Zero-pad the decimals.
elif isinstance(f, meta.FloatField):
elif isinstance(f, models.FloatField):
if field_val is not None:
result_repr = ('%%.%sf' % f.decimal_places) % field_val
else:

View File

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

View File

@ -7,12 +7,12 @@ class AdminApplistNode(template.Node):
self.varname = varname
def render(self, context):
from django.core import meta
from django.db import models
from django.utils.text import capfirst
app_list = []
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:]
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.conf import settings
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.exceptions import Http404, ViewDoesNotExist
from django.core import template, urlresolvers
from django.contrib.admin import utils
from django.models.core import sites
import inspect, os, re
# Exclude methods starting with these strings from documentation
@ -136,7 +136,7 @@ def model_index(request):
return missing_docutils_page(request)
models = []
for app in meta.get_installed_model_modules():
for app in models.get_installed_model_modules():
for model in app._MODELS:
opts = model._meta
models.append({
@ -152,7 +152,7 @@ def model_detail(request, model):
return missing_docutils_page(request)
try:
model = meta.get_app(model)
model = models.get_app(model)
except ImportError:
raise Http404
opts = model.Klass._meta

View File

@ -1,9 +1,9 @@
# Generic admin views.
from django.contrib.admin.views.decorators import staff_member_required
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.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.extensions import DjangoContext as Context
from django.core.extensions import get_object_or_404, render_to_response
@ -13,6 +13,7 @@ try:
from django.models.admin import log
except ImportError:
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.httpwrappers import HttpResponse, HttpResponseRedirect
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):
"Helper function that returns a tuple of (module, opts), raising Http404 if necessary."
try:
mod = meta.get_module(app_label, module_name)
mod = models.get_module(app_label, module_name)
except ImportError:
raise Http404 # Invalid app or module name. Maybe it's not in INSTALLED_APPS.
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]
# Normalize it to new-style ordering.
ordering = meta.handle_legacy_orderlist(ordering)
ordering = models.handle_legacy_orderlist(ordering)
if ordering[0].startswith('-'):
order_field, order_type = ordering[0][1:], 'desc'
@ -171,10 +172,10 @@ class ChangeList(object):
try:
try:
f = lookup_opts.get_field(lookup_opts.admin.list_display[int(params[ORDER_VAR])])
except meta.FieldDoesNotExist:
except models.FieldDoesNotExist:
pass
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
except (IndexError, ValueError):
pass # Invalid ordering specified. Just use the default.
@ -196,10 +197,10 @@ class ChangeList(object):
lookup_order_field = order_field
try:
f = lookup_opts.get_field(order_field)
except meta.FieldDoesNotExist:
except models.FieldDoesNotExist:
pass
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)
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)
@ -211,10 +212,10 @@ class ChangeList(object):
for field_name in lookup_opts.admin.list_display:
try:
f = lookup_opts.get_field(field_name)
except meta.FieldDoesNotExist:
except models.FieldDoesNotExist:
pass
else:
if isinstance(f.rel, meta.ManyToOne):
if isinstance(f.rel, models.ManyToOne):
lookup_params['select_related'] = True
break
lookup_params['order_by'] = ((order_type == 'desc' and '-' or '') + lookup_order_field,)
@ -223,7 +224,7 @@ class ChangeList(object):
for bit in query.split():
or_queries = []
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))
lookup_params['complex'] = reduce(operator.and_, complex_queries)
if opts.one_to_one_field:
@ -247,14 +248,14 @@ def change_list(request, app_label, module_name):
'admin/change_list'], context_instance=c)
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):
# Put in any necessary JavaScript imports.
js = ['js/core.js', 'js/admin/RelatedObjectLookups.js']
if auto_populated_fields:
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'])
if ordered_objects:
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:
try:
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'])
raise StopIteration
except StopIteration:
@ -281,12 +282,12 @@ class AdminBoundField(BoundField):
super(AdminBoundField, self).__init__(field, field_mapping, original)
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.is_date_time = isinstance(field, meta.DateTimeField)
self.is_file_field = isinstance(field, meta.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.hidden = isinstance(self.field, meta.AutoField)
self.is_date_time = isinstance(field, models.DateTimeField)
self.is_file_field = isinstance(field, models.FileField)
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, models.AutoField)
self.first = False
classes = []
@ -307,10 +308,10 @@ class AdminBoundField(BoundField):
if getattr(self, '_display_filled', False):
return
# HACK
if isinstance(self.field.rel, meta.ManyToOne):
if isinstance(self.field.rel, models.ManyToOne):
func_name = 'get_%s' % self.field.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
self._display = ", ".join([str(obj) for obj in self._fetch_existing_display(func_name)])
self._display_filled = True
@ -354,7 +355,7 @@ class AdminBoundManipulator(BoundManipulator):
self.coltype = self.ordered_objects and 'colMS' or 'colM'
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 ''
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()
if request.POST:
new_data = request.POST.copy()
if opts.has_field_type(meta.FileField):
if opts.has_field_type(models.FileField):
new_data.update(request.FILES)
errors = manipulator.get_validation_errors(new_data)
manipulator.do_html2python(new_data)
@ -476,7 +477,7 @@ def change_stage(request, app_label, module_name, object_id):
if request.POST:
new_data = request.POST.copy()
if opts.has_field_type(meta.FileField):
if opts.has_field_type(models.FileField):
new_data.update(request.FILES)
errors = manipulator.get_validation_errors(new_data)
@ -558,7 +559,7 @@ def _get_deleted_objects(deleted_objects, perms_needed, user, obj, opts, current
continue
opts_seen.append(related.opts)
rel_opts_name = related.get_method_name_part()
if isinstance(related.field.rel, meta.OneToOne):
if isinstance(related.field.rel, models.OneToOne):
try:
sub_obj = getattr(obj, 'get_%s' % rel_opts_name)()
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.utils.translation import gettext_lazy as _
class Comment(meta.Model):
user = meta.ForeignKey(auth.User, raw_id_admin=True)
content_type = meta.ForeignKey(core.ContentType)
object_id = meta.IntegerField(_('object ID'))
headline = meta.CharField(_('headline'), maxlength=255, blank=True)
comment = meta.TextField(_('comment'), maxlength=3000)
rating1 = meta.PositiveSmallIntegerField(_('rating #1'), blank=True, null=True)
rating2 = meta.PositiveSmallIntegerField(_('rating #2'), blank=True, null=True)
rating3 = meta.PositiveSmallIntegerField(_('rating #3'), blank=True, null=True)
rating4 = meta.PositiveSmallIntegerField(_('rating #4'), blank=True, null=True)
rating5 = meta.PositiveSmallIntegerField(_('rating #5'), blank=True, null=True)
rating6 = meta.PositiveSmallIntegerField(_('rating #6'), blank=True, null=True)
rating7 = meta.PositiveSmallIntegerField(_('rating #7'), blank=True, null=True)
rating8 = meta.PositiveSmallIntegerField(_('rating #8'), blank=True, null=True)
class Comment(models.Model):
user = models.ForeignKey(auth.User, raw_id_admin=True)
content_type = models.ForeignKey(core.ContentType)
object_id = models.IntegerField(_('object ID'))
headline = models.CharField(_('headline'), maxlength=255, blank=True)
comment = models.TextField(_('comment'), maxlength=3000)
rating1 = models.PositiveSmallIntegerField(_('rating #1'), blank=True, null=True)
rating2 = models.PositiveSmallIntegerField(_('rating #2'), blank=True, null=True)
rating3 = models.PositiveSmallIntegerField(_('rating #3'), blank=True, null=True)
rating4 = models.PositiveSmallIntegerField(_('rating #4'), blank=True, null=True)
rating5 = models.PositiveSmallIntegerField(_('rating #5'), blank=True, null=True)
rating6 = models.PositiveSmallIntegerField(_('rating #6'), blank=True, null=True)
rating7 = models.PositiveSmallIntegerField(_('rating #7'), 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
# functions (summaries). We need this because people are allowed to post
# multiple reviews on the same thing, but the system will only use the
# latest one (with valid_rating=True) in tallying the reviews.
valid_rating = meta.BooleanField(_('is valid rating'))
submit_date = meta.DateTimeField(_('date/time submitted'), auto_now_add=True)
is_public = meta.BooleanField(_('is public'))
ip_address = meta.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.'))
site = meta.ForeignKey(core.Site)
valid_rating = models.BooleanField(_('is valid rating'))
submit_date = models.DateTimeField(_('date/time submitted'), auto_now_add=True)
is_public = models.BooleanField(_('is public'))
ip_address = models.IPAddressField(_('IP address'), blank=True, null=True)
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 = models.ForeignKey(core.Site)
class META:
db_table = 'comments'
verbose_name = _('Comment')
@ -43,7 +43,7 @@ class Comment(meta.Model):
'IS_PUBLIC': 'ip',
}
ordering = ('-submit_date',)
admin = meta.Admin(
admin = models.Admin(
fields = (
(None, {'fields': ('content_type', 'object_id', 'site')}),
('Content', {'fields': ('user', 'headline', 'comment')}),
@ -155,24 +155,24 @@ class Comment(meta.Model):
return True
return False
class FreeComment(meta.Model):
class FreeComment(models.Model):
# A FreeComment is a comment by a non-registered user.
content_type = meta.ForeignKey(core.ContentType)
object_id = meta.IntegerField(_('object ID'))
comment = meta.TextField(_('comment'), maxlength=3000)
person_name = meta.CharField(_("person's name"), maxlength=50)
submit_date = meta.DateTimeField(_('date/time submitted'), auto_now_add=True)
is_public = meta.BooleanField(_('is public'))
ip_address = meta.IPAddressField(_('ip address'))
content_type = models.ForeignKey(core.ContentType)
object_id = models.IntegerField(_('object ID'))
comment = models.TextField(_('comment'), maxlength=3000)
person_name = models.CharField(_("person's name"), maxlength=50)
submit_date = models.DateTimeField(_('date/time submitted'), auto_now_add=True)
is_public = models.BooleanField(_('is public'))
ip_address = models.IPAddressField(_('ip address'))
# TODO: Change this to is_removed, like Comment
approved = meta.BooleanField(_('approved by staff'))
site = meta.ForeignKey(core.Site)
approved = models.BooleanField(_('approved by staff'))
site = models.ForeignKey(core.Site)
class META:
db_table = 'comments_free'
verbose_name = _('Free comment')
verbose_name_plural = _('Free comments')
ordering = ('-submit_date',)
admin = meta.Admin(
admin = models.Admin(
fields = (
(None, {'fields': ('content_type', 'object_id', 'site')}),
('Content', {'fields': ('person_name', 'comment')}),
@ -203,11 +203,11 @@ class FreeComment(meta.Model):
get_content_object.short_description = _('Content object')
class KarmaScore(meta.Model):
user = meta.ForeignKey(auth.User)
comment = meta.ForeignKey(Comment)
score = meta.SmallIntegerField(_('score'), db_index=True)
scored_date = meta.DateTimeField(_('score date'), auto_now=True)
class KarmaScore(models.Model):
user = models.ForeignKey(auth.User)
comment = models.ForeignKey(Comment)
score = models.SmallIntegerField(_('score'), db_index=True)
scored_date = models.DateTimeField(_('score date'), auto_now=True)
class META:
module_name = 'karma'
verbose_name = _('Karma score')
@ -242,10 +242,10 @@ class KarmaScore(meta.Model):
return DEFAULT_KARMA
return int(round((4.5 * score) + 5.5))
class UserFlag(meta.Model):
user = meta.ForeignKey(auth.User)
comment = meta.ForeignKey(Comment)
flag_date = meta.DateTimeField(_('flag date'), auto_now_add=True)
class UserFlag(models.Model):
user = models.ForeignKey(auth.User)
comment = models.ForeignKey(Comment)
flag_date = models.DateTimeField(_('flag date'), auto_now_add=True)
class META:
db_table = 'comments_user_flags'
verbose_name = _('User flag')
@ -272,10 +272,10 @@ class UserFlag(meta.Model):
mail_managers('Comment flagged', message, fail_silently=True)
f.save()
class ModeratorDeletion(meta.Model):
user = meta.ForeignKey(auth.User, verbose_name='moderator')
comment = meta.ForeignKey(Comment)
deletion_date = meta.DateTimeField(_('deletion date'), auto_now_add=True)
class ModeratorDeletion(models.Model):
user = models.ForeignKey(auth.User, verbose_name='moderator')
comment = models.ForeignKey(Comment)
deletion_date = models.DateTimeField(_('deletion date'), auto_now_add=True)
class META:
db_table = 'comments_moderator_deletions'
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.utils.translation import gettext_lazy as _
class FlatPage(meta.Model):
url = meta.CharField(_('URL'), maxlength=100, validator_list=[validators.isAlphaNumericURL],
class FlatPage(models.Model):
url = models.CharField(_('URL'), maxlength=100, validator_list=[validators.isAlphaNumericURL],
help_text=_("Example: '/about/contact/'. Make sure to have leading and trailing slashes."))
title = meta.CharField(_('title'), maxlength=200)
content = meta.TextField(_('content'))
enable_comments = meta.BooleanField(_('enable comments'))
template_name = meta.CharField(_('template name'), maxlength=70, blank=True,
title = models.CharField(_('title'), maxlength=200)
content = models.TextField(_('content'))
enable_comments = models.BooleanField(_('enable comments'))
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'."))
registration_required = meta.BooleanField(_('registration required'), help_text=_("If this is checked, only logged-in users will be able to view the page."))
sites = meta.ManyToManyField(Site)
registration_required = models.BooleanField(_('registration required'), help_text=_("If this is checked, only logged-in users will be able to view the page."))
sites = models.ManyToManyField(Site)
class META:
db_table = 'django_flatpages'
verbose_name = _('flat page')
verbose_name_plural = _('flat pages')
ordering = ('url',)
admin = meta.Admin(
admin = models.Admin(
fields = (
(None, {'fields': ('url', 'title', 'content', 'sites')}),
('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.utils.translation import gettext_lazy as _
class Redirect(meta.Model):
site = meta.ForeignKey(Site, radio_admin=meta.VERTICAL)
old_path = meta.CharField(_('redirect from'), maxlength=200, db_index=True,
class Redirect(models.Model):
site = models.ForeignKey(Site, radio_admin=models.VERTICAL)
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/'."))
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://'."))
class META:
verbose_name = _('redirect')
@ -14,7 +14,7 @@ class Redirect(meta.Model):
db_table = 'django_redirects'
unique_together=(('site', 'old_path'),)
ordering = ('old_path',)
admin = meta.Admin(
admin = models.Admin(
list_filter = ('site',),
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):
"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 = []
for klass in mod._MODELS:
opts = klass._meta
table_output = []
for f in opts.fields:
if isinstance(f, meta.ForeignKey):
if isinstance(f, models.ForeignKey):
rel_field = f.rel.get_related_field()
data_type = get_rel_data_type(rel_field)
else:
@ -233,11 +234,12 @@ get_sql_initial_data.args = APP_ARGS
def get_sql_sequence_reset(mod):
"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 = []
for klass in mod._MODELS:
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));" % \
(klass._meta.db_table, f.column, db.db.quote_name(f.column),
db.db.quote_name(klass._meta.db_table)))
@ -368,9 +370,10 @@ get_admin_index.args = APP_ARGS
def init():
"Initializes the database with auth and core."
try:
from django.core import db, meta
auth = meta.get_app('auth')
core = meta.get_app('core')
from django.core import db
from django.db import models
auth = models.get_app('auth')
core = models.get_app('core')
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):
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 "# into your database."
yield ''
yield 'from django.core import meta'
yield 'from django.db import models'
yield ''
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:
relations = db.get_relations(cursor, table_name)
except NotImplementedError:
@ -588,9 +591,9 @@ def inspectdb(db_name):
rel = relations[i]
rel_to = rel[1] == table_name and "'self'" or table2model(rel[1])
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:
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:
try:
field_type = db.DATA_TYPES_REVERSE[row[1]]
@ -610,7 +613,7 @@ def inspectdb(db_name):
if field_type == 'CharField' and 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 += ')'
if field_type_was_guessed:
@ -634,25 +637,25 @@ class ModelErrorCollection:
def get_validation_errors(outfile):
"Validates all installed models. Writes errors, if any, to outfile. Returns number of errors."
import django.models
from django.core import meta
from django.db import models
e = ModelErrorCollection(outfile)
module_list = meta.get_installed_model_modules()
module_list = models.get_installed_model_modules()
for module in module_list:
for mod in module._MODELS:
opts = mod._meta
# Do field-specific validation.
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)
if isinstance(f, meta.FloatField):
if isinstance(f, models.FloatField):
if f.decimal_places is None:
e.add(opts, '"%s" field: FloatFields require a "decimal_places" attribute.' % f.name)
if f.max_digits is None:
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)
if isinstance(f, meta.ImageField):
if isinstance(f, models.ImageField):
try:
from PIL import Image
except ImportError:
@ -676,8 +679,8 @@ def get_validation_errors(outfile):
# Check admin attribute.
if opts.admin is not None:
if not isinstance(opts.admin, meta.Admin):
e.add(opts, '"admin" attribute, if given, must be set to a meta.Admin() instance.')
if not isinstance(opts.admin, models.Admin):
e.add(opts, '"admin" attribute, if given, must be set to a models.Admin() instance.')
else:
# list_display
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:
try:
f = opts.get_field(fn)
except meta.FieldDoesNotExist:
except models.FieldDoesNotExist:
klass = opts.get_model_module().Klass
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)
else:
if isinstance(f, meta.ManyToManyField):
if isinstance(f, models.ManyToManyField):
e.add(opts, '"admin.list_display" doesn\'t support ManyToManyFields (%r).' % fn)
# list_filter
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:
try:
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)
# Check ordering attribute.
@ -713,7 +716,7 @@ def get_validation_errors(outfile):
continue
try:
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)
# Check core=True, if needed.
@ -731,10 +734,10 @@ def get_validation_errors(outfile):
for field_name in ut:
try:
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)
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)
return len(e.errors)
@ -783,12 +786,13 @@ runserver.args = '[optional port number, or ipaddr:port]'
def createcachetable(tablename):
"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 = (
# "key" is a reserved word in MySQL, so use "cache_key" instead.
meta.CharField(name='cache_key', maxlength=255, unique=True, primary_key=True),
meta.TextField(name='value'),
meta.DateTimeField(name='expires', db_index=True),
models.CharField(name='cache_key', maxlength=255, unique=True, primary_key=True),
models.TextField(name='value'),
models.DateTimeField(name='expires', db_index=True),
)
table_output = []
index_output = []
@ -943,12 +947,12 @@ def execute_from_command_line(action_mapping=DEFAULT_ACTION_MAPPING):
addr, port = '', args[1]
action_mapping[action](addr, port)
else:
from django.core import meta
from django.db import models
if action == 'dbcheck':
mod_list = meta.get_all_installed_modules()
mod_list = models.get_all_installed_modules()
else:
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:
sys.stderr.write("Error: %s. Are you sure your INSTALLED_APPS setting is correct?\n" % e)
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 db
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.text import capfirst
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.utils.translation import gettext_lazy as _
class Permission(meta.Model):
name = meta.CharField(_('name'), maxlength=50)
package = meta.ForeignKey(core.Package, db_column='package')
codename = meta.CharField(_('codename'), maxlength=100)
class Permission(models.Model):
name = models.CharField(_('name'), maxlength=50)
package = models.ForeignKey(core.Package, db_column='package')
codename = models.CharField(_('codename'), maxlength=100)
class META:
verbose_name = _('Permission')
verbose_name_plural = _('Permissions')
@ -15,34 +16,34 @@ class Permission(meta.Model):
def __repr__(self):
return "%s | %s" % (self.package_id, self.name)
class Group(meta.Model):
name = meta.CharField(_('name'), maxlength=80, unique=True)
permissions = meta.ManyToManyField(Permission, blank=True, filter_interface=meta.HORIZONTAL)
class Group(models.Model):
name = models.CharField(_('name'), maxlength=80, unique=True)
permissions = models.ManyToManyField(Permission, blank=True, filter_interface=models.HORIZONTAL)
class META:
verbose_name = _('Group')
verbose_name_plural = _('Groups')
ordering = ('name',)
admin = meta.Admin(
admin = models.Admin(
search_fields = ('name',),
)
def __repr__(self):
return self.name
class User(meta.Model):
username = meta.CharField(_('username'), maxlength=30, unique=True, validator_list=[validators.isAlphaNumeric])
first_name = meta.CharField(_('first name'), maxlength=30, blank=True)
last_name = meta.CharField(_('last name'), maxlength=30, blank=True)
email = meta.EmailField(_('e-mail address'), blank=True)
password = meta.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_active = meta.BooleanField(_('active'), default=True)
is_superuser = meta.BooleanField(_('superuser status'))
last_login = meta.DateTimeField(_('last login'), default=meta.LazyDate())
date_joined = meta.DateTimeField(_('date joined'), default=meta.LazyDate())
groups = meta.ManyToManyField(Group, blank=True,
class User(models.Model):
username = models.CharField(_('username'), maxlength=30, unique=True, validator_list=[validators.isAlphaNumeric])
first_name = models.CharField(_('first name'), maxlength=30, blank=True)
last_name = models.CharField(_('last name'), maxlength=30, blank=True)
email = models.EmailField(_('e-mail address'), blank=True)
password = models.CharField(_('password'), maxlength=128, help_text=_("Use '[algo]$[salt]$[hexdigest]'"))
is_staff = models.BooleanField(_('staff status'), help_text=_("Designates whether the user can log into this admin site."))
is_active = models.BooleanField(_('active'), default=True)
is_superuser = models.BooleanField(_('superuser status'))
last_login = models.DateTimeField(_('last login'), default=models.LazyDate())
date_joined = models.DateTimeField(_('date joined'), default=models.LazyDate())
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."))
user_permissions = meta.ManyToManyField(Permission, blank=True, filter_interface=meta.HORIZONTAL)
user_permissions = models.ManyToManyField(Permission, blank=True, filter_interface=models.HORIZONTAL)
class META:
verbose_name = _('User')
verbose_name_plural = _('Users')
@ -51,7 +52,7 @@ class User(meta.Model):
}
ordering = ('username',)
exceptions = ('SiteProfileNotAvailable',)
admin = meta.Admin(
admin = models.Admin(
fields = (
(None, {'fields': ('username', 'password')}),
(_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
@ -211,9 +212,9 @@ class User(meta.Model):
from random import choice
return ''.join([choice(allowed_chars) for i in range(length)])
class Message(meta.Model):
user = meta.ForeignKey(User)
message = meta.TextField(_('Message'))
class Message(models.Model):
user = models.ForeignKey(User)
message = models.TextField(_('Message'))
def __repr__(self):
return self.message

View File

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

View File

@ -4,11 +4,11 @@
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):
headline = meta.CharField(maxlength=100, default='Default headline')
pub_date = meta.DateTimeField()
class Article(models.Model):
headline = models.CharField(maxlength=100, default='Default headline')
pub_date = models.DateTimeField()
API_TESTS = """
# 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.
"""
from django.core import meta
from django.db import models
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
class Person(meta.Model):
name = meta.CharField(maxlength=20)
gender = meta.CharField(maxlength=1, choices=GENDER_CHOICES)
class Person(models.Model):
name = models.CharField(maxlength=20)
gender = models.CharField(maxlength=1, choices=GENDER_CHOICES)
def __repr__(self):
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.
"""
from django.core import meta
from django.db import models
class Person(meta.Model):
first_name = meta.CharField(maxlength=30, db_column='firstname')
last_name = meta.CharField(maxlength=30, db_column='last')
class Person(models.Model):
first_name = models.CharField(maxlength=30, db_column='firstname')
last_name = models.CharField(maxlength=30, db_column='last')
def __repr__(self):
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.
"""
from django.core import meta
from django.db import models
class Article(meta.Model):
headline = meta.CharField(maxlength=100)
pub_date = meta.DateField()
class Article(models.Model):
headline = models.CharField(maxlength=100)
pub_date = models.DateField()
def __repr__(self):
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.
"""
from django.core import meta
from django.db import models
class Employee(meta.Model):
employee_code = meta.CharField(maxlength=10, primary_key=True)
first_name = meta.CharField(maxlength=20)
last_name = meta.CharField(maxlength=20)
class Employee(models.Model):
employee_code = models.CharField(maxlength=10, primary_key=True)
first_name = models.CharField(maxlength=20)
last_name = models.CharField(maxlength=20)
class META:
ordering = ('last_name', 'first_name')
def __repr__(self):
return "%s %s" % (self.first_name, self.last_name)
class Business(meta.Model):
name = meta.CharField(maxlength=20, primary_key=True)
employees = meta.ManyToManyField(Employee)
class Business(models.Model):
name = models.CharField(maxlength=20, primary_key=True)
employees = models.ManyToManyField(Employee)
class META:
verbose_name_plural = '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."
"""
from django.core import meta
from django.db import models
class Article(meta.Model):
headline = meta.CharField(maxlength=100)
pub_date = meta.DateTimeField()
class Article(models.Model):
headline = models.CharField(maxlength=100)
pub_date = models.DateTimeField()
class META:
get_latest_by = 'pub_date'

View File

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

View File

@ -10,26 +10,26 @@ which specifies the ``Reporter``'s position for the given article (e.g. "Staff
writer").
"""
from django.core import meta
from django.db import models
class Reporter(meta.Model):
first_name = meta.CharField(maxlength=30)
last_name = meta.CharField(maxlength=30)
class Reporter(models.Model):
first_name = models.CharField(maxlength=30)
last_name = models.CharField(maxlength=30)
def __repr__(self):
return "%s %s" % (self.first_name, self.last_name)
class Article(meta.Model):
headline = meta.CharField(maxlength=100)
pub_date = meta.DateField()
class Article(models.Model):
headline = models.CharField(maxlength=100)
pub_date = models.DateField()
def __repr__(self):
return self.headline
class Writer(meta.Model):
reporter = meta.ForeignKey(Reporter)
article = meta.ForeignKey(Article)
position = meta.CharField(maxlength=100)
class Writer(models.Model):
reporter = models.ForeignKey(Reporter)
article = models.ForeignKey(Article)
position = models.CharField(maxlength=100)
def __repr__(self):
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.
"""
from django.core import meta
from django.db import models
class Category(meta.Model):
name = meta.CharField(maxlength=20)
class Category(models.Model):
name = models.CharField(maxlength=20)
class META:
ordering = ('name',)
def __repr__(self):
return self.name
class Article(meta.Model):
headline = meta.CharField(maxlength=50)
pub_date = meta.DateTimeField()
primary_categories = meta.ManyToManyField(Category,
class Article(models.Model):
headline = models.CharField(maxlength=50)
pub_date = models.DateTimeField()
primary_categories = models.ManyToManyField(Category,
singular='primary_category', related_name='primary_article')
secondary_categories = meta.ManyToManyField(Category,
secondary_categories = models.ManyToManyField(Category,
singular='secondary_category', related_name='secondary_article')
class META:
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.
"""
from django.core import meta
from django.db import models
class Category(meta.Model):
name = meta.CharField(maxlength=20)
parent = meta.ForeignKey('self', null=True, related_name='child')
class Category(models.Model):
name = models.CharField(maxlength=20)
parent = models.ForeignKey('self', null=True, related_name='child')
def __repr__(self):
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.
"""
from django.core import meta
from django.db import models
class Person(meta.Model):
full_name = meta.CharField(maxlength=20)
mother = meta.ForeignKey('self', null=True, related_name='mothers_child')
father = meta.ForeignKey('self', null=True, related_name='fathers_child')
class Person(models.Model):
full_name = models.CharField(maxlength=20)
mother = models.ForeignKey('self', null=True, related_name='mothers_child')
father = models.ForeignKey('self', null=True, related_name='fathers_child')
def __repr__(self):
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.
"""
from django.core import meta
from django.db import models
class Publication(meta.Model):
title = meta.CharField(maxlength=30)
class Publication(models.Model):
title = models.CharField(maxlength=30)
def __repr__(self):
return self.title
class Article(meta.Model):
headline = meta.CharField(maxlength=100)
publications = meta.ManyToManyField(Publication)
class Article(models.Model):
headline = models.CharField(maxlength=100)
publications = models.ManyToManyField(Publication)
def __repr__(self):
return self.headline

View File

@ -4,20 +4,20 @@
To define a many-to-one relationship, use ``ForeignKey()`` .
"""
from django.core import meta
from django.db import models
class Reporter(meta.Model):
first_name = meta.CharField(maxlength=30)
last_name = meta.CharField(maxlength=30)
email = meta.EmailField()
class Reporter(models.Model):
first_name = models.CharField(maxlength=30)
last_name = models.CharField(maxlength=30)
email = models.EmailField()
def __repr__(self):
return "%s %s" % (self.first_name, self.last_name)
class Article(meta.Model):
headline = meta.CharField(maxlength=100)
pub_date = meta.DateField()
reporter = meta.ForeignKey(Reporter)
class Article(models.Model):
headline = models.CharField(maxlength=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter)
def __repr__(self):
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`` .
"""
from django.core import meta
from django.db import models
class Reporter(meta.Model):
name = meta.CharField(maxlength=30)
class Reporter(models.Model):
name = models.CharField(maxlength=30)
def __repr__(self):
return self.name
class Article(meta.Model):
headline = meta.CharField(maxlength=100)
reporter = meta.ForeignKey(Reporter, null=True)
class Article(models.Model):
headline = models.CharField(maxlength=100)
reporter = models.ForeignKey(Reporter, null=True)
def __repr__(self):
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``.
"""
from django.core import meta
from django.db import models
class Place(meta.Model):
name = meta.CharField(maxlength=50)
address = meta.CharField(maxlength=80)
class Place(models.Model):
name = models.CharField(maxlength=50)
address = models.CharField(maxlength=80)
def __repr__(self):
return "%s the place" % self.name
class Restaurant(meta.Model):
place = meta.OneToOneField(Place)
serves_hot_dogs = meta.BooleanField()
serves_pizza = meta.BooleanField()
class Restaurant(models.Model):
place = models.OneToOneField(Place)
serves_hot_dogs = models.BooleanField()
serves_pizza = models.BooleanField()
def __repr__(self):
return "%s the restaurant" % self.get_place().name
class Waiter(meta.Model):
restaurant = meta.ForeignKey(Restaurant)
name = meta.CharField(maxlength=50)
class Waiter(models.Model):
restaurant = models.ForeignKey(Restaurant)
name = models.CharField(maxlength=50)
def __repr__(self):
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
``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):
headline = meta.CharField(maxlength=50)
pub_date = meta.DateTimeField()
class Article(models.Model):
headline = models.CharField(maxlength=50)
pub_date = models.DateTimeField()
class META:
ordering = ('pub_date',)
@ -19,7 +19,7 @@ class Article(meta.Model):
API_TESTS = """
>>> 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.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.
"""
from django.core import meta
from django.db import models
class Article(meta.Model):
headline = meta.CharField(maxlength=100)
pub_date = meta.DateTimeField()
class Article(models.Model):
headline = models.CharField(maxlength=100)
pub_date = models.DateTimeField()
class META:
ordering = ('-pub_date', 'headline')

View File

@ -2,11 +2,11 @@
22. Using properties on models
"""
from django.core import meta
from django.db import models
class Person(meta.Model):
first_name = meta.CharField(maxlength=30)
last_name = meta.CharField(maxlength=30)
class Person(models.Model):
first_name = models.CharField(maxlength=30)
last_name = models.CharField(maxlength=30)
def _get_full_name(self):
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.
"""
from django.core import meta
from django.db import models
class Article(meta.Model):
headline = meta.CharField(maxlength=100)
pub_date = meta.DateTimeField()
class Article(models.Model):
headline = models.CharField(maxlength=100)
pub_date = models.DateTimeField()
def __repr__(self):
return self.headline

View File

@ -7,17 +7,17 @@ appropriately behind the scenes, so your database won't complain about
reserved-name usage.
"""
from django.core import meta
from django.db import models
class Thing(meta.Model):
when = meta.CharField(maxlength=1, primary_key=True)
join = meta.CharField(maxlength=1)
like = meta.CharField(maxlength=1)
drop = meta.CharField(maxlength=1)
alter = meta.CharField(maxlength=1)
having = meta.CharField(maxlength=1)
where = meta.CharField(maxlength=1)
has_hyphen = meta.CharField(maxlength=1, db_column='has-hyphen')
class Thing(models.Model):
when = models.CharField(maxlength=1, primary_key=True)
join = models.CharField(maxlength=1)
like = models.CharField(maxlength=1)
drop = models.CharField(maxlength=1)
alter = models.CharField(maxlength=1)
having = models.CharField(maxlength=1)
where = models.CharField(maxlength=1)
has_hyphen = models.CharField(maxlength=1, db_column='has-hyphen')
class META:
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.
"""
from django.core import meta
from django.db import models
class Person(meta.Model):
first_name = meta.CharField(maxlength=20)
last_name = meta.CharField(maxlength=20)
class Person(models.Model):
first_name = models.CharField(maxlength=20)
last_name = models.CharField(maxlength=20)
def __repr__(self):
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.
"""
from django.core import meta
from django.db import models
# From the "Bare-bones model" example
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
# adds a "section" field.
class ArticleWithSection(Article):
section = meta.CharField(maxlength=30)
section = models.CharField(maxlength=30)
# This uses all fields and metadata from Article but
# removes the "pub_date" field.
@ -30,15 +30,15 @@ class ArticleWithoutPubDate(Article):
# This uses all fields and metadata from Article but
# overrides the "pub_date" field.
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',)
# This uses all fields and metadata from ArticleWithRepr and
# makes a few additions/changes.
class ArticleWithManyChanges(ArticleWithRepr):
section = meta.CharField(maxlength=30)
is_popular = meta.BooleanField()
pub_date = meta.DateField() # overrides the old field, a DateTimeField
section = models.CharField(maxlength=30)
is_popular = models.BooleanField()
pub_date = models.DateField() # overrides the old field, a DateTimeField
# This uses all fields from ArticleWithOrdering but
# changes the ordering parameter.
@ -47,10 +47,10 @@ class ArticleWithChangedMeta(ArticleWithOrdering):
ordering = ('headline', 'pub_date')
class NoModuleNameFirst(Article):
section = meta.CharField(maxlength=30)
section = models.CharField(maxlength=30)
class NoModuleNameSecond(Article):
section = meta.CharField(maxlength=30)
section = models.CharField(maxlength=30)
API_TESTS = """
# No data is in the system yet.