Here are the examples of the python api django.db.models.ForeignKey taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
147 Examples
3
Example 1
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Overrides the default widget for Foreignkey fields if they are
specified in the related_search_fields class attribute.
"""
if isinstance(db_field, models.ForeignKey) and \
db_field.name in self.related_search_fields:
kwargs['widget'] = ForeignKeySearchInput(
db_field.rel,
self.related_search_fields[db_field.name],
self.related_string_functions.get(db_field.name),
)
field = super(AutocompleteAdmin, self).formfield_for_dbfield(db_field, **kwargs)
return field
3
Example 2
Project: django-sortedm2m Source File: fields.py
def get_intermediate_model_to_field(self, klass):
name = self.get_intermediate_model_name(klass)
to_model, to_object_name = self.get_rel_to_model_and_object_name(klass)
if self.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to_object_name == klass._meta.object_name:
field_name = 'to_%s' % to_object_name.lower()
else:
field_name = to_object_name.lower()
field = models.ForeignKey(to_model, related_name='%s+' % name,
**get_foreignkey_field_kwargs(self))
return field_name, field
3
Example 3
def get_value_field(self):
return models.ForeignKey, ['color.Color'], {
'null': True,
'blank': True,
'related_name': '+'
}
3
Example 4
@denormalized(models.ForeignKey, Forum, blank=True, null=True)
@depend_on_related(Post)
def forum(self):
if self.post and self.post.forum:
if self.forum_as_object:
# if forum_as_object is set, return forum denorm as an object
return self.post.forum
else:
# otherwise, return as a primary key
return self.post.forum.pk
return None
3
Example 5
def validate_radio_fields(self, cls, model):
" Validate that radio_fields is a dictionary of choice or foreign key fields. "
from django.contrib.admin.options import HORIZONTAL, VERTICAL
if hasattr(cls, 'radio_fields'):
check_isdict(cls, 'radio_fields', cls.radio_fields)
for field, val in cls.radio_fields.items():
f = get_field(cls, model, 'radio_fields', field)
if not (isinstance(f, models.ForeignKey) or f.choices):
raise ImproperlyConfigured("'%s.radio_fields['%s']' "
"is neither an instance of ForeignKey nor does "
"have choices set." % (cls.__name__, field))
if not val in (HORIZONTAL, VERTICAL):
raise ImproperlyConfigured("'%s.radio_fields['%s']' "
"is neither admin.HORIZONTAL nor admin.VERTICAL."
% (cls.__name__, field))
3
Example 6
def test_invalid_base_fields(self):
class InvalidListTextModel(TemporaryModel):
field = ListTextField(
models.ForeignKey('testapp.Author'),
max_length=32
)
errors = InvalidListTextModel.check(actually_check=True)
assert len(errors) == 1
assert errors[0].id == 'django_mysql.E005'
assert 'Base field for list must be' in errors[0].msg
3
Example 7
def handle_model(self):
self.model.add_to_class(
'site',
models.ForeignKey(
Site, verbose_name=_('Site'), default=settings.SITE_ID))
PageManager.add_to_active_filters(current_site, key='current_site')
3
Example 8
def forwards(self, orm):
db.rename_table('image_filer_bucket', 'image_filer_clipboard')
db.rename_table('image_filer_bucketitem', 'image_filer_clipboarditem')
db.rename_field('image_file_clipboarditem.bucket_id', 'image_file_clipboarditem.clipboard_id',)
# Changing field 'Image.folder'
db.alter_column('image_filer_image', 'folder_id', models.ForeignKey(orm.Folder, null=True, blank=True))
3
Example 9
Project: django-admin-customizer Source File: refresh_available_fields.py
def get_type_for(field):
if isinstance(field, models.ForeignKey):
return 'fk'
elif isinstance(field, models.ManyToManyField):
return 'mtm'
elif isinstance(field, models.OneToOneField):
return 'oto'
elif isinstance(field, RelatedObject):
return 'rev'
else:
return 'other'
3
Example 10
Project: django-organizations Source File: base.py
def update_org_users(cls, module):
"""
Adds the `user` field to the organization user model and the link to
the specific organization model.
"""
try:
cls.module_registry[module]['OrgUserModel']._meta.get_field("user")
except FieldDoesNotExist:
cls.module_registry[module]['OrgUserModel'].add_to_class("user",
models.ForeignKey(USER_MODEL, related_name="%(app_label)s_%(class)s"))
try:
cls.module_registry[module]['OrgUserModel']._meta.get_field("organization")
except FieldDoesNotExist:
cls.module_registry[module]['OrgUserModel'].add_to_class("organization",
models.ForeignKey(cls.module_registry[module]['OrgModel'],
related_name="organization_users"))
3
Example 11
def _cache_keys(self, incl_db=True):
"""Return the cache key for self plus all related foreign keys."""
fks = dict((f, getattr(self, f.attname)) for f in self._meta.fields
if isinstance(f, models.ForeignKey))
keys = [fk.rel.to._cache_key(val, incl_db and self._state.db or None)
for fk, val in list(fks.items())
if val is not None and hasattr(fk.rel.to, '_cache_key')]
return (self.get_cache_key(incl_db=incl_db),) + tuple(keys)
3
Example 12
Project: django-parting Source File: tests.py
@cleanup_models('testapp.models.Tweet_foo', 'testapp.models.Star_foo')
def test_get_field_by_name(self):
""" Check that get_field_by_name on a foreign key that was
generated from a PartitionForeignKey returns a real FK, not the
PFK.
"""
from testapp.models import Star, Tweet
Tweet.partitions.get_partition('foo')
star_partition = Star.partitions.get_partition('foo')
fk, _, _, _ = star_partition._meta.get_field_by_name('tweet')
self.assertTrue(isinstance(fk, models.ForeignKey))
3
Example 13
def build_relational_field(self, field_name, relation_info):
if isinstance(relation_info.model_field, model_fields.IntraRegistryForeignKey):
return (api_fields.IntraRegistryForeignKeyField, {'related_model': relation_info.related_model})
elif isinstance(relation_info.model_field, models.ForeignKey):
return (api_fields.ForeignKeyField, {'related_model': relation_info.related_model})
return super(RegistryItemSerializerMixin, self).build_relational_field(field_name, relation_info)
3
Example 14
def _process_field(self, field, parent_fields):
if field in parent_fields:
return
field_name = six.text_type(field.name)
self.list_display.append(field_name)
if isinstance(field, LIST_FILTER):
if isinstance(field, models.ForeignKey):
self._process_foreign_key(field)
else:
self.list_filter.append(field_name)
if field.name in self.search_field_names:
self.search_fields.append(field_name)
return field_name
3
Example 15
def get_field_style(self, attrs, db_field, style, **kwargs):
# search able fk field
if style in ('fk-ajax', 'fk-select') and isinstance(db_field, models.ForeignKey):
if (db_field.remote_field.to in self.admin_view.admin_site._registry) and \
self.has_model_perm(db_field.remote_field.to, 'view'):
db = kwargs.get('using')
return dict(attrs or {}, \
widget=(style == 'fk-ajax' and ForeignKeySearchWidget or ForeignKeySelectWidget)(db_field.remote_field, self.admin_view, using=db))
return attrs
3
Example 16
Project: aldryn-newsblog Source File: 0016_rename_namespace_to_app_config.py
def forwards(self, orm):
rename_tables_old_to_new(db)
# SQLite3 and MySQL NOTE: Altering FK constraints are broken this
# backend, but, its OK to just rename the columns here, because
# constraints are disabled anyway.
if connection.vendor not in ('sqlite', ):
db.drop_foreign_key('aldryn_newsblog_latestentriesplugin', 'namespace_id')
db.rename_column('aldryn_newsblog_latestentriesplugin', 'namespace_id', 'app_config_id')
if connection.vendor not in ('sqlite', 'mysql', ):
db.alter_column('aldryn_newsblog_latestentriesplugin', 'app_config_id',
models.ForeignKey(orm['aldryn_newsblog.NewsBlogConfig']))
if connection.vendor not in ('sqlite', ):
db.drop_foreign_key('aldryn_newsblog_article', 'namespace_id')
db.rename_column('aldryn_newsblog_article', 'namespace_id', 'app_config_id')
if connection.vendor not in ('sqlite', 'mysql', ):
db.alter_column('aldryn_newsblog_article', 'app_config_id',
models.ForeignKey(orm['aldryn_newsblog.NewsBlogConfig']))
3
Example 17
def test_invalid_base_fields(self):
class InvalidSetTextModel(TemporaryModel):
field = SetTextField(
models.ForeignKey('testapp.Author')
)
errors = InvalidSetTextModel.check(actually_check=True)
assert len(errors) == 1
assert errors[0].id == 'django_mysql.E002'
assert 'Base field for set must be' in errors[0].msg
3
Example 18
Project: Geotrek-admin Source File: parsers.py
def apply_filter(self, dst, src, val):
field = self.model._meta.get_field_by_name(dst)[0]
if (isinstance(field, models.ForeignKey) or isinstance(field, models.ManyToManyField)):
if dst not in self.natural_keys:
raise ValueImportError(_(u"Destination field '{dst}' not in natural keys configuration").format(dst=dst))
to = field.rel.to
natural_key = self.natural_keys[dst]
kwargs = self.field_options.get(dst, {})
if isinstance(field, models.ForeignKey):
val = self.filter_fk(src, val, to, natural_key, **kwargs)
else:
val = self.filter_m2m(src, val, to, natural_key, **kwargs)
return val
3
Example 19
def _check_raw_id_fields_item(self, cls, model, field_name, label):
""" Check an item of `raw_id_fields`, i.e. check that field named
`field_name` exists in model `model` and is a ForeignKey or a
ManyToManyField. """
try:
field = model._meta.get_field(field_name)
except FieldDoesNotExist:
return refer_to_missing_field(field=field_name, option=label,
model=model, obj=cls, id='admin.E002')
else:
if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
return must_be('a ForeignKey or ManyToManyField',
option=label, obj=cls, id='admin.E003')
else:
return []
3
Example 20
def get_name_for(field, name):
if isinstance(field, (models.ForeignKey,
models.ManyToManyField,
models.OneToOneField)):
return name
elif isinstance(field, RelatedObject):
return field.get_accessor_name()
else:
return name
3
Example 21
@classmethod
def to_master(cls):
'''
Calculate prefix for filtering times in "at" method.
Override if there are links to/from other docuements.
'''
o = cls._meta
ro = [r for r in o.get_all_related_objects()
if isinstance(r.field, models.ForeignKey)]
d = [r for r in ro if issubclass(r.model, DocuementPart)]
if len(d) == 1:
d = d[0]
if issubclass(d.model, Docuement):
return d.var_name
return d.var_name + '__' + d.model.to_master()
raise cls.ConfigurationError('Master not found - redefine')
3
Example 22
@classmethod
def to_master(cls):
'''
Calculate prefix for filtering times in "at" method.
Override if there are links to/from other docuements.
'''
o = cls._meta
fs = [f for f in o.fields if isinstance(f, models.ForeignKey)]
d = [f for f in fs
if issubclass(f.related.parent_model, DocuementPart)]
if len(d) == 1:
d = d[0]
if issubclass(d.related.parent_model, Docuement):
return d.name
return d.name + '__' + d.related.parent_model.to_master()
raise cls.ConfigurationError('Master not found - redefine')
3
Example 23
def validate_fk_name(self, cls, model):
" Validate that fk_name refers to a ForeignKey. "
if cls.fk_name: # default value is None
f = get_field(cls, model, 'fk_name', cls.fk_name)
if not isinstance(f, models.ForeignKey):
raise ImproperlyConfigured("'%s.fk_name is not an instance of "
"models.ForeignKey." % cls.__name__)
3
Example 24
def validate_fk_name(self, cls, model):
" Validate that fk_name refers to a ForeignKey. "
if cls.fk_name: # default value is None
f = get_field(cls, model, 'fk_name', cls.fk_name)
if not isinstance(f, models.ForeignKey):
raise ImproperlyConfigured("'%s.fk_name is not an instance of "
"models.ForeignKey." % cls.__name__)
3
Example 25
def get_queryset(self):
qs = self.get_super_queryset()
if self.instance is None:
return qs
if isinstance(self.instance._meta.pk, models.ForeignKey):
key_name = self.instance._meta.pk.name + "_id"
else:
key_name = self.instance._meta.pk.name
return self.get_super_queryset().filter(**{key_name: self.instance.pk})
3
Example 26
def _check_raw_id_fields_item(self, obj, model, field_name, label):
""" Check an item of `raw_id_fields`, i.e. check that field named
`field_name` exists in model `model` and is a ForeignKey or a
ManyToManyField. """
try:
field = model._meta.get_field(field_name)
except FieldDoesNotExist:
return refer_to_missing_field(field=field_name, option=label,
model=model, obj=obj, id='admin.E002')
else:
if not field.many_to_many and not isinstance(field, models.ForeignKey):
return must_be('a foreign key or a many-to-many field',
option=label, obj=obj, id='admin.E003')
else:
return []
3
Example 27
Project: django-fixture-magic Source File: utils.py
def serialize_fully():
index = 0
while index < len(serialize_me):
for field in get_fields(serialize_me[index]):
if isinstance(field, models.ForeignKey):
add_to_serialize_list(
[serialize_me[index].__getattribute__(field.name)])
index += 1
serialize_me.reverse()
3
Example 28
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Overrides the default widget for Foreignkey fields if they are
specified in the related_search_fields class attribute.
"""
if (isinstance(db_field, models.ForeignKey) and
db_field.name in self.related_search_fields):
model_name = db_field.rel.to._meta.object_name
help_text = self.get_help_text(db_field.name, model_name)
if kwargs.get('help_text'):
help_text = u'%s %s' % (kwargs['help_text'], help_text)
kwargs['widget'] = ForeignKeySearchInput(db_field.rel,
self.related_search_fields[db_field.name])
kwargs['help_text'] = help_text
return super(ForeignKeyAutocompleteAdmin,
self).formfield_for_dbfield(db_field, **kwargs)
3
Example 29
Project: django-denorm Source File: helpers.py
def find_fks(from_model, to_model, fk_name=None):
"""
Finds all ForeignKeys on 'from_model' pointing to 'to_model'.
If 'fk_name' is given only ForeignKeys matching that name are returned.
"""
# get all ForeignKeys
fkeys = [x for x in from_model._meta.fields if isinstance(x, models.ForeignKey)]
# filter out all FKs not pointing to 'to_model'
fkeys = [x for x in fkeys if repr(remote_field_model(x)).lower() == repr(to_model).lower()]
# if 'fk_name' was given, filter out all FKs not matching that name, leaving
# only one (or none)
if fk_name:
fk_name = fk_name if isinstance(fk_name, six.string_types) else fk_name.attname
fkeys = [x for x in fkeys if x.attname in (fk_name, fk_name + '_id')]
return fkeys
3
Example 30
def formfield_for_dbfield(self, formfield, db_field, **kwargs):
if formfield and self.model in self.admin_site._registry and isinstance(db_field, (models.ForeignKey, models.ManyToManyField)):
rel_model = get_model_from_relation(db_field)
if rel_model in self.admin_site._registry and self.has_model_perm(rel_model, 'add'):
add_url = self.get_model_url(rel_model, 'add')
formfield.widget = RelatedFieldWidgetWrapper(
formfield.widget, db_field.rel, add_url, self.get_model_url(self.model, 'add'))
return formfield
3
Example 31
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Overrides the default widget for Foreignkey fields if they are
specified in the related_search_fields class attribute.
"""
if isinstance(db_field, models.ForeignKey) and db_field.name in self.related_search_fields:
model_name = db_field.rel.to._meta.object_name
help_text = self.get_help_text(db_field.name, model_name)
if kwargs.get('help_text'):
help_text = six.u('%s %s' % (kwargs['help_text'], help_text))
kwargs['widget'] = ForeignKeySearchInput(db_field.rel, self.related_search_fields[db_field.name])
kwargs['help_text'] = help_text
return super(ForeignKeyAutocompleteAdminMixin, self).formfield_for_dbfield(db_field, **kwargs)
3
Example 32
Project: django-mysql Source File: test_listcharfield.py
def test_invalid_base_fields(self):
class InvalidListCharModel(TemporaryModel):
field = ListCharField(
models.ForeignKey('testapp.Author'),
max_length=32
)
errors = InvalidListCharModel.check(actually_check=True)
assert len(errors) == 1
assert errors[0].id == 'django_mysql.E005'
assert 'Base field for list must be' in errors[0].msg
3
Example 33
def get_target_value(self, start_model, field_chain, pk):
fields = field_chain.split('__')
foreign_key = start_model._meta.get_field(fields[0])
if not foreign_key.rel:
# field isn't a related one, so return the value itself
return pk
target_model = foreign_key.rel.to
foreignkey = target_model.objects.all().get(pk=pk)
for value in fields[1:-1]:
foreignkey = getattr(foreignkey, value)
if isinstance(foreignkey._meta.get_field(fields[-1]), models.ForeignKey):
return getattr(foreignkey, '%s_id' % fields[-1])
else:
return getattr(foreignkey, fields[-1])
3
Example 34
Project: chain-api Source File: api.py
@classmethod
def sanitize_field_value(cls, field_name, value):
'''Converts the given value to the correct python tyhttp://localhost:8080/people/1pe, for instance if
the field is supposed to be a float field and the string "23" is given,
it will be converted to 23.0
NOTE - this currently only works for vanilla model fields, which serves
our purposes for now'''
field = cls.model._meta.get_field_by_name(field_name)[0]
field_class = field.__class__
if field_class == models.ForeignKey:
lookup = lookup_associated_model_object(value)
if lookup is None:
raise BadRequestException(
"The url to the given resource does not exist.")
return lookup
return field.to_python(value)
3
Example 35
Project: django-moderation Source File: testmodels.py
def setUp(self):
from tests.models import CustomUser,\
UserProfileWithCustomUser
from django.conf import settings
self.user = CustomUser.objects.create(
username='custom_user',
password='aaaa')
self.copy_m = ModeratedObject.by
ModeratedObject.by = models.ForeignKey(
getattr(settings, 'AUTH_USER_MODEL', 'auth.User'),
blank=True, null=True, editable=False,
related_name='moderated_objects')
self.profile = UserProfileWithCustomUser.objects.create(
user=self.user,
description='Old description',
url='http://google.com')
self.moderation = setup_moderation([UserProfileWithCustomUser])
3
Example 36
def test_invalid_base_fields(self):
class InvalidSetCharFieldModel(TemporaryModel):
field = SetCharField(
models.ForeignKey('testapp.Author'),
max_length=32
)
errors = InvalidSetCharFieldModel.check(actually_check=True)
assert len(errors) == 1
assert errors[0].id == 'django_mysql.E002'
assert 'Base field for set must be' in errors[0].msg
3
Example 37
Project: django-fakery Source File: values.py
def fake_value(self, model, field):
if isinstance(field, models.ForeignKey):
return self.factory.make_one(field.related_model, iteration=self.iteration)
if field.name in field_mappings.mappings_names:
return self.evaluate_fake(field_mappings.mappings_names[field.name], field)
for field_class, fake in field_mappings.mappings_types.items():
if isinstance(field, field_class):
return self.evaluate_fake(fake, field)
model_name = '%s.%s' % (model._meta.app_label, model._meta.model_name)
raise ValueError('Cant generate a value for model `%s` field `%s`' % (model_name, field.name))
3
Example 38
@filter_hook
def get_field_style(self, db_field, style, **kwargs):
if style in ('radio', 'radio-inline') and (db_field.choices or isinstance(db_field, models.ForeignKey)):
attrs = {'widget': widgets.AdminRadioSelect(
attrs={'inline': 'inline' if style == 'radio-inline' else ''})}
if db_field.choices:
attrs['choices'] = db_field.get_choices(
include_blank=db_field.blank,
blank_choice=[('', _('Null'))]
)
return attrs
if style in ('checkbox', 'checkbox-inline') and isinstance(db_field, models.ManyToManyField):
return {'widget': widgets.AdminCheckboxSelect(attrs={'inline': style == 'checkbox-inline'}),
'help_text': None}
3
Example 39
def handle_model(self):
self.model.add_to_class('symlinked_page', models.ForeignKey(
'self',
blank=True,
null=True,
related_name='%(app_label)s_%(class)s_symlinks',
verbose_name=_('symlinked page'),
help_text=_('All content is inherited from this page if given.')))
@monkeypatch_property(self.model)
def content(self):
if not hasattr(self, '_content_proxy'):
if self.symlinked_page:
self._content_proxy = self.content_proxy_class(
self.symlinked_page)
else:
self._content_proxy = self.content_proxy_class(self)
return self._content_proxy
3
Example 40
def _check_raw_id_fields_item(self, obj, model, field_name, label):
""" Check an item of `raw_id_fields`, i.e. check that field named
`field_name` exists in model `model` and is a ForeignKey or a
ManyToManyField. """
try:
field = model._meta.get_field(field_name)
except FieldDoesNotExist:
return refer_to_missing_field(field=field_name, option=label,
model=model, obj=obj, id='admin.E002')
else:
if not isinstance(field, (models.ForeignKey, models.ManyToManyField)):
return must_be('a ForeignKey or ManyToManyField',
option=label, obj=obj, id='admin.E003')
else:
return []
3
Example 41
Project: django-sortedm2m Source File: fields.py
def get_intermediate_model_from_field(self, klass):
name = self.get_intermediate_model_name(klass)
to_model, to_object_name = self.get_rel_to_model_and_object_name(klass)
if self.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to_object_name == klass._meta.object_name:
field_name = 'from_%s' % to_object_name.lower()
else:
field_name = get_model_name(klass)
field = models.ForeignKey(klass, related_name='%s+' % name,
**get_foreignkey_field_kwargs(self))
return field_name, field
3
Example 42
Project: PyClassLessons Source File: validation.py
def validate_raw_id_fields(self, cls, model):
" Validate that raw_id_fields only contains field names that are listed on the model. "
if hasattr(cls, 'raw_id_fields'):
check_isseq(cls, 'raw_id_fields', cls.raw_id_fields)
for idx, field in enumerate(cls.raw_id_fields):
f = get_field(cls, model, 'raw_id_fields', field)
if not isinstance(f, (models.ForeignKey, models.ManyToManyField)):
raise ImproperlyConfigured("'%s.raw_id_fields[%d]', '%s' must "
"be either a ForeignKey or ManyToManyField."
% (cls.__name__, idx, field))
3
Example 43
def register(cls):
"""
generuje TreePathModel dla podanego modelu
:param cls:
:return:
"""
tpcls = type(cls.__name__ + 'TreePath',
(TreePathModel,),
{'__module__': cls.__module__})
ancestor_field = models.ForeignKey(cls, related_name='tpa')
descendant_field = models.ForeignKey(cls, related_name='tpd')
ancestor_field.contribute_to_class(tpcls, 'ancestor')
descendant_field.contribute_to_class(tpcls, 'descendant')
cls._tpm = tpcls
cls._cls = cls
return tpcls
3
Example 44
Project: django-sellmo Source File: price.py
def construct_extra_model_fields(self):
return {
'tax': models.ForeignKey(
'tax.Tax',
null=True,
blank=True,
related_name='+'
)
}
3
Example 45
def backwards(self, orm):
#db.rename_field('image_file_clipboarditem.clipboard_id','image_file_clipboarditem.bucket_id')
db.rename_table('image_filer_clipboard' ,'image_file_bucket')
db.rename_table('image_filer_clipboard_item', 'image_file_bucket_item')
# Changing field 'Image.folder'
db.alter_column('image_filer_image', 'folder_id', models.ForeignKey(orm.Folder, null=True, blank=True))
3
Example 46
def test_fields(self):
c = Client()
self.run_client(c)
owner = PropertyOwner.objects.get(pk = 1)
prop = Property.objects.get(pk = 1)
self.assertEqual(prop.audit_log.all()[0]._meta.get_field('owned_by').__class__, models.ForeignKey)
3
Example 47
def validate_radio_fields(self, cls, model):
" Validate that radio_fields is a dictionary of choice or foreign key fields. "
from django.contrib.admin.options import HORIZONTAL, VERTICAL
if hasattr(cls, 'radio_fields'):
check_isdict(cls, 'radio_fields', cls.radio_fields)
for field, val in cls.radio_fields.items():
f = get_field(cls, model, 'radio_fields', field)
if not (isinstance(f, models.ForeignKey) or f.choices):
raise ImproperlyConfigured("'%s.radio_fields['%s']' "
"is neither an instance of ForeignKey nor does "
"have choices set." % (cls.__name__, field))
if val not in (HORIZONTAL, VERTICAL):
raise ImproperlyConfigured("'%s.radio_fields['%s']' "
"is neither admin.HORIZONTAL nor admin.VERTICAL."
% (cls.__name__, field))
3
Example 48
def copy(self, orm, OldModel, NewModel):
old_field = new_field = None
for field in orm.Source._meta.fields:
if isinstance(field, models.ForeignKey):
if field.rel.to == orm.Storage:
old_field = field
elif field.rel.to == orm.StorageNew:
new_field = field
assert old_field and new_field
for storage in OldModel.objects.all():
new_storage = NewModel()
for key in [f.attname for f in OldModel._meta.fields]:
setattr(new_storage, key, getattr(storage, key))
new_storage.save()
filter_kwargs = {old_field.name: storage}
update_kwargs = {new_field.name: new_storage}
for Model in (orm.Source, orm.Thumbnail):
Model.objects.filter(**filter_kwargs).update(**update_kwargs)
3
Example 49
Project: wagtail-commons Source File: utils.py
def transformation_for_model_field(model, attr_name, model_mapper):
# If a transformation is specified, use that
mapped_transformation = model_mapper.get(attr_name, None)
if mapped_transformation:
return transformation_for_name(mapped_transformation)
(field_object, model, direct, m2m) = model._meta.get_field_by_name(attr_name)
if isinstance(field_object, models.ForeignKey):
return transformation_for_foreign_key(field_object)
else:
return transformation_for_field(field_object)
return identity
3
Example 50
def validate_inline(cls):
# model is already verified to exist and be a Model
if cls.fk_name: # default value is None
f = get_field(cls, cls.model, cls.model._meta, 'fk_name', cls.fk_name)
if not isinstance(f, models.ForeignKey):
raise ImproperlyConfigured("'%s.fk_name is not an instance of "
"models.ForeignKey." % cls.__name__)
# extra = 3
# max_num = 0
for attr in ('extra', 'max_num'):
if not isinstance(getattr(cls, attr), int):
raise ImproperlyConfigured("'%s.%s' should be a integer."
% (cls.__name__, attr))
# formset
if hasattr(cls, 'formset') and not issubclass(cls.formset, BaseModelFormSet):
raise ImproperlyConfigured("'%s.formset' does not inherit from "
"BaseModelFormSet." % cls.__name__)