我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.ForeignKey()。
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 []
def formfield(self, **kwargs): db = kwargs.pop('using', None) if isinstance(self.remote_field.model, six.string_types): raise ValueError("Cannot create form field for %r yet, because " "its related model %r has not been loaded yet" % (self.name, self.remote_field.model)) defaults = { 'form_class': forms.ModelChoiceField, 'queryset': self.remote_field.model._default_manager.using(db), 'to_field_name': self.remote_field.field_name, } defaults.update(kwargs) return super(ForeignKey, self).formfield(**defaults)
def save_user_profile(sender, instance, **kwargs): instance.profile.save() # class ParsedProfile(models.Model): # user = models.OneToOneField(User, on_delete=models.CASCADE) # name = models.CharField(max_length=250) # header = models.CharField(max_length=500, null=True) # url = models.CharField(max_length=500) # school = models.CharField(max_length=500, null=True) # school_program = models.CharField(max_length=500, null=True) # # # class JobTitle(models.Model): # profile = models.ForeignKey(ParsedProfile, on_delete=models.CASCADE) # job = models.CharField(max_length=500, null=True) # # # class Location(models.Model): # profile = models.ForeignKey(ParsedProfile, on_delete=models.CASCADE) # loc = models.CharField(max_length=500, default=None) # Below is All The Profiles that were originally in DB and added new ones by User # Initial Profiles, only 2000 were in DB (mainly SE/CS focused)
def backwards(self, orm): # Rename field 'file._file' db.rename_column('filer_file', 'file', '_file') # Deleting field 'File.is_public' db.delete_column('filer_file', 'is_public') # no need to do this. south just *thinks* something has changed, because it did not know anything about through in earlier versions # Adding M2M table for field files on 'clipboard' # db.create_table('filer_clipboard_files', ( # ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), # ('clipboard', models.ForeignKey(orm['filer.clipboard'], null=False)), # ('file', models.ForeignKey(orm['filer.file'], null=False)) # )) # db.create_unique('filer_clipboard_files', ['clipboard_id', 'file_id'])
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) )
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 ), hint=None, obj=obj.__class__, id='admin.E023', ) ] else: return []
def validate(self, value, model_instance): if self.remote_field.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.remote_field.model._default_manager.using(using).filter( **{self.remote_field.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.remote_field.model._meta.verbose_name, 'pk': value, 'field': self.remote_field.field_name, 'value': value, }, # 'pk' is included for backwards compatibility )
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 []
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 []
def _check_prepopulated_fields_key(self, obj, model, field_name, label): """ Check a key of `prepopulated_fields` dictionary, i.e. check that it is a name of existing field and the field is one of the allowed types. """ 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.E027') else: if isinstance(field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)): return [ checks.Error( "The value of '%s' refers to '%s', which must not be a DateTimeField, " "a ForeignKey, or a ManyToManyField." % (label, field_name), obj=obj.__class__, id='admin.E028', ) ] else: return []
def _check_prepopulated_fields_key(self, obj, model, field_name, label): """ Check a key of `prepopulated_fields` dictionary, i.e. check that it is a name of existing field and the field is one of the allowed types. """ 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.E027') else: if isinstance(field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)): return [ checks.Error( "The value of '%s' refers to '%s', which must not be a DateTimeField, " "a ForeignKey, a OneToOneField, or a ManyToManyField." % (label, field_name), obj=obj.__class__, id='admin.E028', ) ] else: return []
def process_field(cls, field): """ Processes a given field on the model Resolves attributes/fields from the fields related model :param field: ForeignKey field from the parent model :return: Dict of related field data """ field_map = {} for descriptor_class in cls.get_descriptor_classes(): descriptor = descriptor_class.for_model(field.rel.to) field_map.update(descriptor) return dict([ ForeignKeyDescriptor.field_data(field, other_model_field) for other_model_field in field_map.items() ])
def __str__(self): return self.caption # class Cpu(models.Model): # # host = models.OneToOneField('Host') ???? # server = models.ForeignKey('Host') # cpu_model = models.CharField(verbose_name='CPU??', max_length=128,null=True) # cpu_count = models.SmallIntegerField(verbose_name='??CPU??',null=True) # cpu_core_count = models.SmallIntegerField(verbose_name='CPU???',null=True) # use = models.CharField(verbose_name='???',max_length=32,null=True) # memo = models.TextField(verbose_name='??', null=True,) # create_date = models.DateTimeField(auto_now_add=True, verbose_name='????') # update_date = models.DateTimeField(auto_now=True, null=True, verbose_name='????') # # class Meta: # db_table = 'Cpu' # verbose_name = 'CPU??' # verbose_name_plural = verbose_name # # unique_together=("host","cpu_model") ???? # # def __str__(self): # return self.cpu_model
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)
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 []
def formfield_for_foreignkey(self, db_field, request=None, **kwargs): """ Get a form Field for a ForeignKey. """ db = kwargs.get('using') if db_field.name in self.raw_id_fields: kwargs['widget'] = widgets.ForeignKeyRawIdWidget(db_field.rel, 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)
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'])
def get_field_docs(self, fieldname): try: field = self.model._meta.get_field(fieldname) if isinstance(field, models.ForeignKey): return _serializers[field.rel.to].docs() elif isinstance(field, models.ManyToManyField): spec = _serializers[field.rel.to].docs() spec['array'] = True return spec elif isinstance(field, models.ManyToOneRel): spec = _serializers[field.related_model].docs() spec['array'] = True return spec return FieldDocs(self.model, field) except models.FieldDoesNotExist: model = getattr(self.model, fieldname).related.related_model spec = _serializers[model].docs() spec['array'] = True return spec
def __init__(self, **kwargs): # We hard-code the `to` argument for ForeignKey.__init__ dfl = get_model_label(self.default_model_class) if "to" in kwargs.keys(): # pragma: no cover old_to = get_model_label(kwargs.pop("to")) if old_to != dfl: msg = "%s can only be a ForeignKey to %s; %s passed" % ( self.__class__.__name__, dfl, old_to ) warnings.warn(msg, SyntaxWarning) kwargs['to'] = dfl super(FilerFolderField, self).__init__(**kwargs)
def south_field_triple(self): "Returns a suitable description of this field for South." # We'll just introspect ourselves, since we inherit. from south.modelsinspector import introspector field_class = "django.db.models.fields.related.ForeignKey" args, kwargs = introspector(self) # That's our definition! return (field_class, args, kwargs)
def __init__(self, **kwargs): # We hard-code the `to` argument for ForeignKey.__init__ dfl = get_model_label(self.default_model_class) if "to" in kwargs.keys(): # pragma: no cover old_to = get_model_label(kwargs.pop("to")) if old_to != dfl: msg = "%s can only be a ForeignKey to %s; %s passed" % ( self.__class__.__name__, dfl, old_to ) warnings.warn(msg, SyntaxWarning) kwargs['to'] = dfl super(FilerFileField, self).__init__(**kwargs)
def generic_inlineformset_factory(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, validate_max=False, for_concrete_model=True, min_num=None, validate_min=False): """ Returns a ``GenericInlineFormSet`` for the given kwargs. You must provide ``ct_field`` and ``fk_field`` if they are different from the defaults ``content_type`` and ``object_id`` respectively. """ opts = model._meta # if there is no field called `ct_field` let the exception propagate ct_field = opts.get_field(ct_field) if not isinstance(ct_field, models.ForeignKey) or ct_field.remote_field.model != ContentType: raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field) fk_field = opts.get_field(fk_field) # let the exception propagate if exclude is not None: exclude = list(exclude) exclude.extend([ct_field.name, fk_field.name]) else: exclude = [ct_field.name, fk_field.name] FormSet = modelformset_factory(model, form=form, formfield_callback=formfield_callback, formset=formset, extra=extra, can_delete=can_delete, can_order=can_order, fields=fields, exclude=exclude, max_num=max_num, validate_max=validate_max, min_num=min_num, validate_min=validate_min) FormSet.ct_field = ct_field FormSet.ct_fk_field = fk_field FormSet.for_concrete_model = for_concrete_model return FormSet
def _check_prepopulated_fields_key(self, obj, model, field_name, label): """ Check a key of `prepopulated_fields` dictionary, i.e. check that it is a name of existing field and the field is one of the allowed types. """ forbidden_field_types = ( models.DateTimeField, models.ForeignKey, models.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.E027') else: if isinstance(field, forbidden_field_types): return [ checks.Error( "The value of '%s' refers to '%s', which must not be a DateTimeField, " "ForeignKey or ManyToManyField." % ( label, field_name ), hint=None, obj=obj.__class__, id='admin.E028', ) ] else: return []
def deconstruct(self): name, path, args, kwargs = super(ForeignObject, self).deconstruct() kwargs['on_delete'] = self.remote_field.on_delete kwargs['from_fields'] = self.from_fields kwargs['to_fields'] = self.to_fields if self.remote_field.related_name is not None: kwargs['related_name'] = self.remote_field.related_name if self.remote_field.related_query_name is not None: kwargs['related_query_name'] = self.remote_field.related_query_name if self.remote_field.parent_link: kwargs['parent_link'] = self.remote_field.parent_link # Work out string form of "to" if isinstance(self.remote_field.model, six.string_types): kwargs['to'] = self.remote_field.model else: kwargs['to'] = "%s.%s" % ( self.remote_field.model._meta.app_label, self.remote_field.model._meta.object_name, ) # If swappable is True, then see if we're actually pointing to the target # of a swap. swappable_setting = self.swappable_setting if swappable_setting is not None: # If it's already a settings reference, error if hasattr(kwargs['to'], "setting_name"): if kwargs['to'].setting_name != swappable_setting: raise ValueError( "Cannot deconstruct a ForeignKey pointing to a model " "that is swapped in place of more than one model (%s and %s)" % (kwargs['to'].setting_name, swappable_setting) ) # Set it from django.db.migrations.writer import SettingsReference kwargs['to'] = SettingsReference( kwargs['to'], swappable_setting, ) return name, path, args, kwargs
def check(self, **kwargs): errors = super(ForeignKey, self).check(**kwargs) errors.extend(self._check_on_delete()) errors.extend(self._check_unique()) return errors
def _check_unique(self, **kwargs): return [ checks.Warning( 'Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.', hint='ForeignKey(unique=True) is usually better served by a OneToOneField.', obj=self, id='fields.W342', ) ] if self.unique else []