我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.Model()。
def resolve_relation(scope_model, relation): """ Transform relation into a model or fully-qualified model string of the form "app_label.ModelName", relative to scope_model. The relation argument can be: * RECURSIVE_RELATIONSHIP_CONSTANT, i.e. the string "self", in which case the model argument will be returned. * A bare model name without an app_label, in which case scope_model's app_label will be prepended. * An "app_label.ModelName" string. * A model class, which will be returned unchanged. """ # Check for recursive relations if relation == RECURSIVE_RELATIONSHIP_CONSTANT: relation = scope_model # Look for an "app.Model" relation if isinstance(relation, six.string_types): if "." not in relation: relation = "%s.%s" % (scope_model._meta.app_label, relation) return relation
def register(self, model, include_fields=[], exclude_fields=[]): """ Register a model with actionslog. Actionslog will then track mutations on this model's instances. :param model: The model to register. :type model: Model :param include_fields: The fields to include. Implicitly excludes all other fields. :type include_fields: list :param exclude_fields: The fields to exclude. Overrides the fields to include. :type exclude_fields: list """ if issubclass(model, Model): self._registry[model] = { 'include_fields': include_fields, 'exclude_fields': exclude_fields, } self._connect_signals(model) else: raise TypeError("Supplied model is not a valid model.")
def get_fields_in_model(instance): """ Returns the list of fields in the given model instance. Checks whether to use the official _meta API or use the raw data. This method excludes many to many fields. :param instance: The model instance to get the fields for :type instance: Model :return: The list of fields for the given model (instance) :rtype: list """ assert isinstance(instance, Model) # Check if the Django 1.8 _meta API is available use_api = hasattr(instance._meta, 'get_fields') and callable(instance._meta.get_fields) if use_api: return [f for f in instance._meta.get_fields() if track_field(f)] return instance._meta.fields
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 test_undefined(self): from django.db import models from django.db.models import fields class UndefinedClass(models.Model): pass alias = adapter.DjangoClassAlias(UndefinedClass, None) x = UndefinedClass() alias.applyAttributes(x, { 'id': pyamf.Undefined }) self.assertEqual(x.id, fields.NOT_PROVIDED) x.id = fields.NOT_PROVIDED attrs = alias.getEncodableAttributes(x) self.assertEqual(attrs, {'id': pyamf.Undefined})
def test_non_field_prop(self): from django.db import models class Book(models.Model): def _get_number_of_odd_pages(self): return 234 # note the lack of a setter callable .. numberOfOddPages = property(_get_number_of_odd_pages) alias = adapter.DjangoClassAlias(Book, 'Book') x = Book() self.assertEqual( alias.getEncodableAttributes(x), {'numberOfOddPages': 234, 'id': None} ) # now we test sending the numberOfOddPages attribute alias.applyAttributes(x, {'numberOfOddPages': 24, 'id': None}) # test it hasn't been set self.assertEqual(x.numberOfOddPages, 234)
def model_format_dict(obj): """ Return a `dict` with keys 'verbose_name' and 'verbose_name_plural', typically for use with string formatting. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. """ if isinstance(obj, (models.Model, models.base.ModelBase)): opts = obj._meta elif isinstance(obj, models.query.QuerySet): opts = obj.model._meta else: opts = obj return { 'verbose_name': force_text(opts.verbose_name), 'verbose_name_plural': force_text(opts.verbose_name_plural) }
def model_ngettext(obj, n=None): """ Return the appropriate `verbose_name` or `verbose_name_plural` value for `obj` depending on the count `n`. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. If `obj` is a `QuerySet` instance, `n` is optional and the length of the `QuerySet` is used. """ if isinstance(obj, models.query.QuerySet): if n is None: n = obj.count() obj = obj.model d = model_format_dict(obj) singular, plural = d["verbose_name"], d["verbose_name_plural"] return ungettext(singular, plural, n or 0)
def deconstruct(self): kwargs = { 'name': self.name, 'fields': self.fields, } if self.options: kwargs['options'] = self.options if self.bases and self.bases != (models.Model,): kwargs['bases'] = self.bases if self.managers and self.managers != [('objects', models.Manager())]: kwargs['managers'] = self.managers return ( self.__class__.__name__, [], kwargs )
def get_normalized_value(value, lhs): from django.db.models import Model if isinstance(value, Model): value_list = [] sources = lhs.output_field.get_path_info()[-1].target_fields for source in sources: while not isinstance(value, source.model) and source.remote_field: source = source.remote_field.model._meta.get_field(source.remote_field.field_name) try: value_list.append(getattr(value, source.attname)) except AttributeError: # A case like Restaurant.objects.filter(place=restaurant_instance), # where place is a OneToOneField and the primary key of Restaurant. return (value.pk,) return tuple(value_list) if not isinstance(value, tuple): return (value,) return value
def test_get_i18n_index_name(self): self.assertEquals( get_i18n_index_name(Blog), 'app_blog_i18n_gin' ) class LongDBTableModel(models.Model): class Meta: app_label = 'test_app' self.assertEquals( get_i18n_index_name(LongDBTableModel), 'test_app_7ed506_i18n_gin' ) class LongAppnameModel(models.Model): class Meta: app_label = 'app_name_is_very_long' self.assertEquals( get_i18n_index_name(LongAppnameModel), 'app_name_is_ve_4fab22_i18n_gin' )
def test_get_i18n_field(self): self.assertEquals(get_i18n_field(app_models.Blog), app_models.Blog._meta.get_field('i18n')) class I18nFieldTestModel(models.Model): test = models.CharField(max_length=20) class Meta: app_label = 'django-modeltrans_tests' self.assertEquals(get_i18n_field(I18nFieldTestModel), None) class I18nFieldTestModel2(models.Model): test = models.CharField(max_length=20) i18n = models.CharField(max_length=20) class Meta: app_label = 'django-modeltrans_tests' self.assertEquals(get_i18n_field(I18nFieldTestModel2), None)
def test_translate_model_with_existing_field(self): class TestModel2(models.Model): title = models.CharField(max_length=100) title_nl = models.CharField(max_length=100) i18n = TranslationField(fields=('title', )) class Meta: app_label = 'django-modeltrans_tests' expected_message = ( 'Error adding translation field. Model "TestModel2" already ' 'contains a field named "title_nl".' ) with self.assertRaisesMessage(ImproperlyConfigured, expected_message): translate_model(TestModel2)
def test_translate_without_virtual_fields(self): class TestModel4(models.Model): title = models.CharField(max_length=100) i18n = TranslationField(fields=('title', ), virtual_fields=False) class Meta: app_label = 'django-modeltrans_tests' m = TestModel4(title='foo') self.assertTrue(hasattr(m, 'i18n')) self.assertFalse(hasattr(m, 'title_i18n')) self.assertFalse(hasattr(m, 'title_en')) expected_message = "'title_nl' is an invalid keyword argument for this function" with self.assertRaisesMessage(TypeError, expected_message): TestModel4(title='bar', title_nl='foo')
def _resolve_attribute(self, instance, attr_name): """ Helper method for resolving a value from a given attribute on the model instance. Will call methods and return their returned data values :param instance: The model instance we're getting data from :type instance: django.db.models.Model :param attr_name: The name of the attribute we're resolving :type attr_name: str|unicode :return: unicode string """ value = '' model_class = self.content_type.model_class() for descriptor_class in self.CSV_GENERATOR_ATTRIBUTE_DESCRIPTOR_CLASSES: descriptor = descriptor_class.for_model(model_class) try: value = descriptor.resolve(instance, attr_name) except DescriptorException: continue else: break return value
def model_format_dict(obj): """ Return a `dict` with keys 'verbose_name' and 'verbose_name_plural', typically for use with string formatting. `obj` may be a `Model` instance, `Model` subclass, or `QuerySet` instance. """ if isinstance(obj, (models.Model, models.base.ModelBase)): opts = obj._meta elif isinstance(obj, models.query.QuerySet): opts = obj.model._meta else: opts = obj return { 'verbose_name': force_unicode(opts.verbose_name), 'verbose_name_plural': force_unicode(opts.verbose_name_plural) }
def mantaince(self): if datetime.date.today() - self.updated_at.days > 30: self.prog_stats["no_of_users_this_month"] = 0 # class ProgStat(models.Model): # ''' # no_of_users: integer # no_of_users_this_month: integer # ''' # no_of_users = models.IntegerField(default='0') # no_of_users_this_month = models.IntegerField(default='0') # class Mentors(models.Model): # ''' # Mentor name and id # ''' # name = models.CharField(max_length=64) # mid = models.IntegerField(default='0')
def check_reverse_relation(model, related_name): """ Helper method to check if a given model related_name pair return a reverse relation instance that is associated by a ForeignKey. model: subclass of django.db.models.Model related_name: str """ rel = get_reverse_relation(model, related_name) if rel is None: raise NotImplementedError( '{} does not have a reverse relation by the name "{}"'.format( model.__name__, related_name ) ) elif not isinstance(rel, ManyToOneRel): raise TypeError( 'The reverse relation "{}" on {}.{} is not a ForeignKey.' 'Timeseries only works with ForeignKey reverse relations.'.format( related_name, rel.field.model.__name__, rel.field.name ) ) return rel
def check_created_field(model): """ Helper method to check if a given model has a created field. model must me a class that inherits from django.db.models.Model """ try: created = model._meta.get_field_by_name('created') assert isinstance(created, models.DateTimeField) except FieldDoesNotExist as err: raise FieldDoesNotExist( 'Reverse related model {} must have a created field.\n'.format( model.__name__ ) + str(err) ) except AssertionError: raise TypeError( '{}.created field must be a DateTimeField'.format(model.__name__) )
def _resolve_model(obj): """ Resolve supplied `obj` to a Django model class. `obj` must be a Django model class itself, or a string representation of one. Useful in situations like GH #1225 where Django may not have resolved a string-based reference to a model in another model's foreign key definition. String representations should have the format: 'appname.ModelName' """ if isinstance(obj, six.string_types) and len(obj.split('.')) == 2: app_name, model_name = obj.split('.') resolved_model = apps.get_model(app_name, model_name) if resolved_model is None: msg = "Django did not return a model for {0}.{1}" raise ImproperlyConfigured(msg.format(app_name, model_name)) return resolved_model elif inspect.isclass(obj) and issubclass(obj, models.Model): return obj raise ValueError("{0} is not a Django model".format(obj))
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 _cached_get_or_create(self, clazz, **kwargs): """ This is a memory-cached get_or_create. We assume that the objects will not be created in the database through any other means. """ assert issubclass(clazz, models.Model), "_cached_get_or_create needs to get the class as first argument" key = ORMWrapper._build_key(**kwargs) dictname = "objects_%s" % clazz.__name__ if not dictname in vars(self).keys(): vars(self)[dictname] = {} created = False if not key in vars(self)[dictname].keys(): vars(self)[dictname][key], created = \ clazz.objects.get_or_create(**kwargs) return (vars(self)[dictname][key], created)
def get_session_form_data_as_list(self, request, job_name): """ Retrieve form data that was serialized to the session in :func:`~django_admin_rq.admin.JobAdminMixin.job_form` Values prefixed with 'contenttype:' are replace with the instantiated Model versions. """ form_data = [] serialized_data = self.get_session_data(request, job_name).get('form_data', []) for field_data in copy.deepcopy(serialized_data): # Don't modify the serialized session data value = field_data['value'] if isinstance(value, six.string_types): if value.startswith(_CONTENT_TYPE_PREFIX): match = re.search(_CONTENT_TYPE_RE_PATTERN, value) if match: field_data['value'] = ContentType.objects.get( app_label=match.group(1), model=match.group(2) ).get_object_for_this_type(**{ 'pk': match.group(3) }) form_data.append(field_data) return form_data
def __init__(self, queryset): # convert the provided argument from a Model class into a QuerySet as needed if isinstance(queryset, type) and issubclass(queryset, models.Model): queryset = queryset.objects.all() self.queryset = queryset self.tables = [] self.left_join_tables = [] self.where = [] # import auth models here to avoid circular imports from .models import Role, Collection, Membership, FacilityUser # retrieve the table names that will be used as context for building queries self._table_names = { "role_table": Role._meta.db_table, "collection_table": Collection._meta.db_table, "membership_table": Membership._meta.db_table, "facilityuser_table": FacilityUser._meta.db_table, }
def validate_inlines(self, cls, model): " Validate inline model admin classes. " from django.contrib.admin.options import BaseModelAdmin if hasattr(cls, 'inlines'): check_isseq(cls, 'inlines', cls.inlines) for idx, inline in enumerate(cls.inlines): if not issubclass(inline, BaseModelAdmin): raise ImproperlyConfigured("'%s.inlines[%d]' does not inherit " "from BaseModelAdmin." % (cls.__name__, idx)) if not inline.model: raise ImproperlyConfigured("'model' is a required attribute " "of '%s.inlines[%d]'." % (cls.__name__, idx)) if not issubclass(inline.model, models.Model): raise ImproperlyConfigured("'%s.inlines[%d].model' does not " "inherit from models.Model." % (cls.__name__, idx)) inline.validate(inline.model) self.check_inline(inline, model)
def validate(self, request): """ Verify the given request is associated with this redirect. """ if not self.hash_string or not self.salt: raise AttributeError("Model is not yet populated.") if not request.session.exists(request.session.session_key): # install session in database request.session.create() req_hash = self.generate_hash(request.session.session_key, self.salt) state = request.GET.get('state', None) if req_hash == state: # ensures state is a match for the request session if req_hash == self.hash_string: # ensures the request session is a match for this redirect return True return False
def _post_save(sender, **kwargs): if _autostart_disabled or sender not in _registered_models: return autostart_if = _registered_models[sender] obj = kwargs['instance'] # XXX: 'raw' is passed during fixture loading, but that's an undocumented feature - see django bug #13299 (FMD1) if not kwargs.get('raw') and autostart_if(obj, kwargs['created']): from ecs.workflow.models import Workflow, Graph cts = [ContentType.objects.get_for_model(cls) for cls in sender.__mro__ if issubclass(cls, Model) and cls != Model and not cls._meta.abstract] graphs = Graph.objects.filter(content_type__in=cts, auto_start=True) for graph in graphs: wf = graph.create_workflow(data=obj) wf.start() # HACK