當前位置: 首頁>>代碼示例>>Python>>正文


Python models.ForeignKey方法代碼示例

本文整理匯總了Python中django.db.models.ForeignKey方法的典型用法代碼示例。如果您正苦於以下問題:Python models.ForeignKey方法的具體用法?Python models.ForeignKey怎麽用?Python models.ForeignKey使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.db.models的用法示例。


在下文中一共展示了models.ForeignKey方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: allow_search_fields

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def allow_search_fields(cls, exclude=None):
    opts = cls._meta
    if not exclude:
        exclude = ['onidc', 'slug', 'created', 'modified']
    exclude.extend([f.name for f in opts.fields if getattr(f, 'choices')])
    fields = []
    for f in opts.fields:
        if exclude and f.name in exclude:
            continue
        if isinstance(f, models.ForeignKey):
            submodel = f.related_model
            for sub in submodel._meta.fields:
                if exclude and sub.name in exclude:
                    continue
                if isinstance(sub, models.CharField) \
                        and not getattr(sub, 'choices'):
                    fields.append(f.name + '__' + sub.name + '__icontains')
        if isinstance(f, models.CharField):
            fields.append(f.name + '__icontains')
    return fields 
開發者ID:Wenvki,項目名稱:django-idcops,代碼行數:22,代碼來源:utils.py

示例2: deconstruct

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def deconstruct(self):
        name, path, args, kwargs = super(ForeignKey, self).deconstruct()
        del kwargs['to_fields']
        del kwargs['from_fields']
        # Handle the simpler arguments
        if self.db_index:
            del kwargs['db_index']
        else:
            kwargs['db_index'] = False
        if self.db_constraint is not True:
            kwargs['db_constraint'] = self.db_constraint
        # Rel needs more work.
        to_meta = getattr(self.rel.to, "_meta", None)
        if self.rel.field_name and (not to_meta or (to_meta.pk and self.rel.field_name != to_meta.pk.name)):
            kwargs['to_field'] = self.rel.field_name
        return name, path, args, kwargs 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:18,代碼來源:related.py

示例3: validate

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def validate(self, value, model_instance):
        if self.rel.parent_link:
            return
        super(ForeignKey, self).validate(value, model_instance)
        if value is None:
            return

        using = router.db_for_read(model_instance.__class__, instance=model_instance)
        qs = self.rel.to._default_manager.using(using).filter(
            **{self.rel.field_name: value}
        )
        qs = qs.complex_filter(self.get_limit_choices_to())
        if not qs.exists():
            raise exceptions.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
                params={
                    'model': self.rel.to._meta.verbose_name, 'pk': value,
                    'field': self.rel.field_name, 'value': value,
                },  # 'pk' is included for backwards compatibility
            ) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:23,代碼來源:related.py

示例4: _check_raw_id_fields_item

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
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 [] 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:18,代碼來源:checks.py

示例5: _check_radio_fields_key

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def _check_radio_fields_key(self, cls, model, field_name, label):
        """ Check that a key of `radio_fields` dictionary is name of existing
        field and that the field is a ForeignKey or has `choices` defined. """

        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.E022')
        else:
            if not (isinstance(field, models.ForeignKey) or field.choices):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which is not an "
                        "instance of ForeignKey, and does not have a 'choices' definition." % (
                            label, field_name
                        ),
                        hint=None,
                        obj=cls,
                        id='admin.E023',
                    )
                ]
            else:
                return [] 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:26,代碼來源:checks.py

示例6: validate_prepopulated_fields

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def validate_prepopulated_fields(self, cls, model):
        " Validate that prepopulated_fields if a dictionary  containing allowed field types. "
        # prepopulated_fields
        if hasattr(cls, 'prepopulated_fields'):
            check_isdict(cls, 'prepopulated_fields', cls.prepopulated_fields)
            for field, val in cls.prepopulated_fields.items():
                f = get_field(cls, model, 'prepopulated_fields', field)
                if isinstance(f, (models.DateTimeField, models.ForeignKey,
                        models.ManyToManyField)):
                    raise ImproperlyConfigured("'%s.prepopulated_fields['%s']' "
                            "is either a DateTimeField, ForeignKey or "
                            "ManyToManyField. This isn't allowed."
                            % (cls.__name__, field))
                check_isseq(cls, "prepopulated_fields['%s']" % field, val)
                for idx, f in enumerate(val):
                    get_field(cls, model, "prepopulated_fields['%s'][%d]" % (field, idx), f) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:18,代碼來源:validation.py

示例7: verify_fk

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def verify_fk(self, feat, rel_model, rel_mapping):
        """
        Given an OGR Feature, the related model and its dictionary mapping,
        this routine will retrieve the related model for the ForeignKey
        mapping.
        """
        # TODO: It is expensive to retrieve a model for every record --
        #  explore if an efficient mechanism exists for caching related
        #  ForeignKey models.

        # Constructing and verifying the related model keyword arguments.
        fk_kwargs = {}
        for field_name, ogr_name in rel_mapping.items():
            fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))

        # Attempting to retrieve and return the related model.
        try:
            return rel_model.objects.using(self.using).get(**fk_kwargs)
        except ObjectDoesNotExist:
            raise MissingForeignKey(
                'No ForeignKey %s model found with keyword arguments: %s' %
                (rel_model.__name__, fk_kwargs)
            ) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:25,代碼來源:layermapping.py

示例8: has_perm

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def has_perm(self, user, permission):
    if user.is_superuser:
        return True
    if isinstance(permission, six.string_types):
        permission = [permission, ]
    if user.has_perms(permission):
        return True
    if self._authorization_meta.owner_field and self._authorization_meta.owner_permission and \
       self._authorization_meta.owner_permission in permission and \
       user.pk == getattr(self, self._authorization_meta.owner_field).pk:
        return True
    paths = self._authorization_meta.model.get_authorization_paths(user, permission)
    if not paths.count():
        return False
    for field in self._authorization_meta.fields:
        f = self._meta.get_field(field)
        relation = getattr(self, field)
        if isinstance(f, models.ManyToManyField):
            qs_filter = reduce(lambda x, y: x | y, [Q(path__startswith=path) for path in paths])
            if relation.filter(qs_filter).distinct().exists():
                return True
        elif isinstance(f, models.ForeignKey):
            if relation is not None and any(relation.path.startswith(p) for p in paths):
                return True
    return False 
開發者ID:certsocietegenerale,項目名稱:FIR,代碼行數:27,代碼來源:decorator.py

示例9: forwards

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def forwards(self, orm):
        # Adding model 'Project'
        db.create_table('api_project', (
            ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
            ('organization', self.gf('django.db.models.fields.related.ForeignKey')(related_name='project_organization', to=orm['auth.User'])),
            ('created_by', self.gf('django.db.models.fields.related.ForeignKey')(related_name='project_creator', to=orm['auth.User'])),
            ('date_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('date_modified', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
        ))
        db.send_create_signal('api', ['Project'])

        # Adding unique constraint on 'Project', fields ['name', 'organization']
        db.create_unique('api_project', ['name', 'organization_id'])

        # Adding M2M table for field projects on 'Team'
        db.create_table('api_team_projects', (
            ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
            ('team', models.ForeignKey(orm['api.team'], null=False)),
            ('project', models.ForeignKey(orm['api.project'], null=False))
        ))
        db.create_unique('api_team_projects', ['team_id', 'project_id']) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:24,代碼來源:0002_auto__add_project__add_unique_project_name_organization.py

示例10: _check_raw_id_fields_item

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
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 [] 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:18,代碼來源:checks.py

示例11: _check_radio_fields_key

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def _check_radio_fields_key(self, obj, model, field_name, label):
        """ Check that a key of `radio_fields` dictionary is name of existing
        field and that the field is a ForeignKey or has `choices` defined. """

        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.E022')
        else:
            if not (isinstance(field, models.ForeignKey) or field.choices):
                return [
                    checks.Error(
                        "The value of '%s' refers to '%s', which is not an "
                        "instance of ForeignKey, and does not have a 'choices' definition." % (
                            label, field_name
                        ),
                        obj=obj.__class__,
                        id='admin.E023',
                    )
                ]
            else:
                return [] 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:25,代碼來源:checks.py

示例12: formfield_for_foreignkey

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def formfield_for_foreignkey(self, db_field, request, **kwargs):
        """
        Get a form Field for a ForeignKey.
        """
        db = kwargs.get('using')

        if db_field.name in self.get_autocomplete_fields(request):
            kwargs['widget'] = AutocompleteSelect(db_field.remote_field, self.admin_site, using=db)
        elif db_field.name in self.raw_id_fields:
            kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.remote_field, self.admin_site, using=db)
        elif db_field.name in self.radio_fields:
            kwargs['widget'] = widgets.AdminRadioSelect(attrs={
                'class': get_ul_class(self.radio_fields[db_field.name]),
            })
            kwargs['empty_label'] = _('None') if db_field.blank else None

        if 'queryset' not in kwargs:
            queryset = self.get_field_queryset(db, db_field, request)
            if queryset is not None:
                kwargs['queryset'] = queryset

        return db_field.formfield(**kwargs) 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:24,代碼來源:options.py

示例13: verify_fk

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def verify_fk(self, feat, rel_model, rel_mapping):
        """
        Given an OGR Feature, the related model and its dictionary mapping,
        retrieve the related model for the ForeignKey mapping.
        """
        # TODO: It is expensive to retrieve a model for every record --
        #  explore if an efficient mechanism exists for caching related
        #  ForeignKey models.

        # Constructing and verifying the related model keyword arguments.
        fk_kwargs = {}
        for field_name, ogr_name in rel_mapping.items():
            fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))

        # Attempting to retrieve and return the related model.
        try:
            return rel_model.objects.using(self.using).get(**fk_kwargs)
        except ObjectDoesNotExist:
            raise MissingForeignKey(
                'No ForeignKey %s model found with keyword arguments: %s' %
                (rel_model.__name__, fk_kwargs)
            ) 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:24,代碼來源:layermapping.py

示例14: _get_field_type

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def _get_field_type(field):
    if isinstance(field, models.ForeignKey):
        if django.VERSION >= (2, 0):
            to = field.remote_field.model
            if isinstance(to, str):
                to = _resolve_model(field, to)
        else:
            to = field.rel.to
            if isinstance(to, str):
                to = _resolve_model(field, to)

        return u":type %s: %s to :class:`~%s.%s`" % (
            field.name,
            type(field).__name__,
            to.__module__,
            to.__name__,
        )
    else:
        return u":type %s: %s" % (field.name, type(field).__name__) 
開發者ID:edoburu,項目名稱:sphinxcontrib-django,代碼行數:21,代碼來源:docstrings.py

示例15: test_model_init_params

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import ForeignKey [as 別名]
def test_model_init_params(self):
        """Model __init__ gets all fields as params."""
        lines = []
        docstrings._add_model_fields_as_params(self.app, SimpleModel, lines)
        self.assertEqual(
            lines,
            [
                ":param id: Id",
                ":type id: AutoField",
                ":param user: User",
                ":type user: ForeignKey to :class:`~django.contrib.auth.models.User`",
                ":param user2: User2",
                ":type user2: ForeignKey to"
                " :class:`~sphinxcontrib_django.tests.test_docstrings.User2`",
                ":param user3: User3",
                ":type user3: ForeignKey to :class:`~django.contrib.auth.models.User`",
                ":param dummy_field: Dummy field",
                ":type dummy_field: CharField",
            ],
        ) 
開發者ID:edoburu,項目名稱:sphinxcontrib-django,代碼行數:22,代碼來源:test_docstrings.py


注:本文中的django.db.models.ForeignKey方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。