我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.OneToOneField()。
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 __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 _register_model(admin, model): if not hasattr(admin, 'reversion_format'): admin.reversion_format = 'json' if not is_registered(model): inline_fields = [] for inline in getattr(admin, 'inlines', []): inline_model = inline.model if getattr(inline, 'generic_inline', False): ct_field = getattr(inline, 'ct_field', 'content_type') ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id') for field in model._meta.many_to_many: if isinstance(field, GenericRelation) \ and field.rel.to == inline_model \ and field.object_id_field_name == ct_fk_field \ and field.content_type_field_name == ct_field: inline_fields.append(field.name) _autoregister(admin, inline_model) else: fk_name = getattr(inline, 'fk_name', None) if not fk_name: for field in inline_model._meta.fields: if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.rel.to): fk_name = field.name _autoregister(admin, inline_model, follow=[fk_name]) if not inline_model._meta.get_field(fk_name).rel.is_hidden(): accessor = inline_model._meta.get_field(fk_name).remote_field.get_accessor_name() inline_fields.append(accessor) _autoregister(admin, model, inline_fields)
def get_fields(cls, model): """ Method for getting the fields required for processing by the descriptor :param model: The model the get fields for :type model: django.db.models.Model :return: list of model fields """ return list(filter( lambda x: not isinstance(x, (models.ForeignKey, models.ManyToManyField, models.OneToOneField)), model._meta.fields ))
def add_fields(self, form, index): """Add a hidden field for the object's primary key.""" from django.db.models import AutoField, OneToOneField, ForeignKey self._pk_field = pk = self.model._meta.pk # If a pk isn't editable, then it won't be on the form, so we need to # add it here so we can tell which object is which when we get the # data back. Generally, pk.editable should be false, but for some # reason, auto_created pk fields and AutoField's editable attribute is # True, so check for that as well. def pk_is_not_editable(pk): return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or (pk.rel and pk.rel.parent_link and pk_is_not_editable(pk.rel.to._meta.pk))) if pk_is_not_editable(pk) or pk.name not in form.fields: if form.is_bound: # If we're adding the related instance, ignore its primary key # as it could be an auto-generated default which isn't actually # in the database. pk_value = None if form.instance._state.adding else form.instance.pk else: try: if index is not None: pk_value = self.get_queryset()[index].pk else: pk_value = None except IndexError: pk_value = None if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey): qs = pk.rel.to._default_manager.get_queryset() else: qs = self.model._default_manager.get_queryset() qs = qs.using(form.instance._state.db) if form._meta.widgets: widget = form._meta.widgets.get(self._pk_field.name, HiddenInput) else: widget = HiddenInput form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=widget) super(BaseModelFormSet, self).add_fields(form, index)
def _register_model(admin, model): if not hasattr(admin, 'revision_manager'): admin.revision_manager = default_revision_manager if not hasattr(admin, 'reversion_format'): admin.reversion_format = 'json' if not admin.revision_manager.is_registered(model): inline_fields = [] for inline in getattr(admin, 'inlines', []): inline_model = inline.model if getattr(inline, 'generic_inline', False): ct_field = getattr(inline, 'ct_field', 'content_type') ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id') for field in model._meta.many_to_many: if isinstance(field, GenericRelation) and field.rel.to == inline_model and field.object_id_field_name == ct_fk_field and field.content_type_field_name == ct_field: inline_fields.append(field.name) _autoregister(admin, inline_model) else: fk_name = getattr(inline, 'fk_name', None) if not fk_name: for field in inline_model._meta.fields: if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.rel.to): fk_name = field.name _autoregister(admin, inline_model, follow=[fk_name]) if not inline_model._meta.get_field(fk_name).rel.is_hidden(): accessor = inline_model._meta.get_field( fk_name).related.get_accessor_name() inline_fields.append(accessor) _autoregister(admin, model, inline_fields)
def test_change_one_to_one_field_model_sync(self): # Make sure we're not getting ``AttemptedCardinalityViolation`` when trying to # change a OneToOneField constraint. author = AuthorFixture(Author).create_one() user = User.objects.create_user(username='testuser', password='test123.') author.user = user author.save() self.assertEqual(author.user, user)
def get_cardinality_for_field(field): """ Returns the cardinality for ``field``. """ cardinalities = { models.ForeignKey: ZeroOrOne, models.ManyToOneRel: ZeroOrMore, models.OneToOneField: ZeroOrOne, models.OneToOneRel: ZeroOrOne, models.ManyToManyField: ZeroOrMore, models.ManyToManyRel: ZeroOrMore, GenericForeignKey: ZeroOrOne, GenericRelation: ZeroOrMore } return cardinalities[field.__class__]
def _register_model(admin, model): if not hasattr(admin, 'revision_manager'): admin.revision_manager = default_revision_manager if not hasattr(admin, 'reversion_format'): admin.reversion_format = 'json' if not admin.revision_manager.is_registered(model): inline_fields = [] for inline in getattr(admin, 'inlines', []): inline_model = inline.model if getattr(inline, 'generic_inline', False): ct_field = getattr(inline, 'ct_field', 'content_type') ct_fk_field = getattr(inline, 'ct_fk_field', 'object_id') for field in model._meta.many_to_many: if isinstance(field, GenericRelation) \ and field.rel.to == inline_model \ and field.object_id_field_name == ct_fk_field \ and field.content_type_field_name == ct_field: inline_fields.append(field.name) _autoregister(admin, inline_model) else: fk_name = getattr(inline, 'fk_name', None) if not fk_name: for field in inline_model._meta.fields: if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(model, field.rel.to): fk_name = field.name _autoregister(admin, inline_model, follow=[fk_name]) if not inline_model._meta.get_field(fk_name).rel.is_hidden(): accessor = inline_model._meta.get_field(fk_name).remote_field.get_accessor_name() inline_fields.append(accessor) _autoregister(admin, model, inline_fields)
def add_fields(self, form, index): """Add a hidden field for the object's primary key.""" from django.db.models import AutoField, OneToOneField, ForeignKey self._pk_field = pk = self.model._meta.pk # If a pk isn't editable, then it won't be on the form, so we need to # add it here so we can tell which object is which when we get the # data back. Generally, pk.editable should be false, but for some # reason, auto_created pk fields and AutoField's editable attribute is # True, so check for that as well. def pk_is_not_editable(pk): return ((not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or (pk.rel and pk.rel.parent_link and pk_is_not_editable(pk.rel.to._meta.pk))) if pk_is_not_editable(pk) or pk.name not in form.fields: if form.is_bound: pk_value = form.instance.pk else: try: if index is not None: pk_value = self.get_queryset()[index].pk else: pk_value = None except IndexError: pk_value = None if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey): qs = pk.rel.to._default_manager.get_queryset() else: qs = self.model._default_manager.get_queryset() qs = qs.using(form.instance._state.db) if form._meta.widgets: widget = form._meta.widgets.get(self._pk_field.name, HiddenInput) else: widget = HiddenInput form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=widget) super(BaseModelFormSet, self).add_fields(form, index)
def __str__(self): return 'Email: ' + self.user.email # class UserSettings(models.Model): # user = models.OneToOneField(UserProfile,on_delete=models.CASCADE,primary_key=True)
def __init__(self, *args, **kwargs): """Initializes the VersionAdmin""" super(VersionAdmin, self).__init__(*args, **kwargs) # Automatically register models if required. if not self.revision_manager.is_registered(self.model): inline_fields = [] for inline in self.inlines: inline_model = inline.model if issubclass(inline, GenericInlineModelAdmin): ct_field = inline.ct_field ct_fk_field = inline.ct_fk_field for field in self.model._meta.many_to_many: if isinstance(field, GenericRelation) and field.rel.to == inline_model and field.object_id_field_name == ct_fk_field and field.content_type_field_name == ct_field: inline_fields.append(field.name) self._autoregister(inline_model) elif issubclass(inline, options.InlineModelAdmin): fk_name = inline.fk_name if not fk_name: for field in inline_model._meta.fields: if isinstance(field, (models.ForeignKey, models.OneToOneField)) and issubclass(self.model, field.rel.to): fk_name = field.name self._autoregister(inline_model, follow=[fk_name]) if not inline_model._meta.get_field(fk_name).rel.is_hidden(): accessor = inline_model._meta.get_field(fk_name).related.get_accessor_name() inline_fields.append(accessor) self._autoregister(self.model, inline_fields) # Wrap own methods in manual revision management. self.add_view = self.revision_context_manager.create_revision(manage_manually=True)(self.add_view) self.change_view = self.revision_context_manager.create_revision(manage_manually=True)(self.change_view) self.delete_view = self.revision_context_manager.create_revision(manage_manually=True)(self.delete_view) self.recover_view = self.revision_context_manager.create_revision(manage_manually=True)(self.recover_view) self.revision_view = self.revision_context_manager.create_revision(manage_manually=True)(self.revision_view) self.changelist_view = self.revision_context_manager.create_revision(manage_manually=True)(self.changelist_view)
def contribute(cls, payment): return {'payment': models.OneToOneField(payment)}
def request_type_string(self): return REQUEST_TYPES[self.request_type][1] # class UserRequestComments(models.Model): # user = models.OneToOneField( # settings.AUTH_USER_MODEL, related_name='+') # comment = models.TextField() # created_date = models.DateTimeField(default=timezone.now) # class Meta: # ordering = ('created_date',)
def add_fields(self, form, index): """Add a hidden field for the object's primary key.""" from django.db.models import AutoField, OneToOneField, ForeignKey self._pk_field = pk = self.model._meta.pk # If a pk isn't editable, then it won't be on the form, so we need to # add it here so we can tell which object is which when we get the # data back. Generally, pk.editable should be false, but for some # reason, auto_created pk fields and AutoField's editable attribute is # True, so check for that as well. def pk_is_not_editable(pk): return ( (not pk.editable) or (pk.auto_created or isinstance(pk, AutoField)) or ( pk.remote_field and pk.remote_field.parent_link and pk_is_not_editable(pk.remote_field.model._meta.pk) ) ) if pk_is_not_editable(pk) or pk.name not in form.fields: if form.is_bound: # If we're adding the related instance, ignore its primary key # as it could be an auto-generated default which isn't actually # in the database. pk_value = None if form.instance._state.adding else form.instance.pk else: try: if index is not None: pk_value = self.get_queryset()[index].pk else: pk_value = None except IndexError: pk_value = None if isinstance(pk, OneToOneField) or isinstance(pk, ForeignKey): qs = pk.remote_field.model._default_manager.get_queryset() else: qs = self.model._default_manager.get_queryset() qs = qs.using(form.instance._state.db) if form._meta.widgets: widget = form._meta.widgets.get(self._pk_field.name, HiddenInput) else: widget = HiddenInput form.fields[self._pk_field.name] = ModelChoiceField(qs, initial=pk_value, required=False, widget=widget) super(BaseModelFormSet, self).add_fields(form, index)
def __new__(self, model_name, bases, attrs): # print; print '###', model_name, '- bases:', bases # Workaround compatibility issue with six.with_metaclass() and custom Django model metaclasses: if not attrs and model_name == 'NewBase': if django.VERSION < (1, 5): # Let Django fully ignore the class which is inserted in between. # Django 1.5 fixed this, see https://code.djangoproject.com/ticket/19688 attrs['__module__'] = 'django.utils.six' attrs['Meta'] = type('Meta', (), {'abstract': True}) return super(PolymorphicModelBase, self).__new__(self, model_name, bases, attrs) # create new model new_class = self.call_superclass_new_method(model_name, bases, attrs) # check if the model fields are all allowed self.validate_model_fields(new_class) # create list of all managers to be inherited from the base classes inherited_managers = new_class.get_inherited_managers(attrs) # add the managers to the new model for source_name, mgr_name, manager in inherited_managers: # print '** add inherited manager from model %s, manager %s, %s' % (source_name, mgr_name, manager.__class__.__name__) new_manager = manager._copy_to_model(new_class) if mgr_name == '_default_manager': new_class._default_manager = new_manager else: new_class.add_to_class(mgr_name, new_manager) # get first user defined manager; if there is one, make it the _default_manager # this value is used by the related objects, restoring access to custom queryset methods on related objects. user_manager = self.get_first_user_defined_manager(new_class) if user_manager: # print '## add default manager', type(def_mgr) new_class._default_manager = user_manager._copy_to_model(new_class) new_class._default_manager._inherited = False # the default mgr was defined by the user, not inherited # validate resulting default manager self.validate_model_manager(new_class._default_manager, model_name, '_default_manager') # for __init__ function of this class (monkeypatching inheritance accessors) new_class.polymorphic_super_sub_accessors_replaced = False # determine the name of the primary key field and store it into the class variable # polymorphic_primary_key_name (it is needed by query.py) for f in new_class._meta.fields: if f.primary_key and type(f) != models.OneToOneField: new_class.polymorphic_primary_key_name = f.name break return new_class