class Restaurant(models.Model): restaurant_ID = AutoField(primary_key=True) owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, blank=True) name = CharField(max_length=100) slug = models.SlugField(unique=True) address = CharField(max_length=100, blank=True, null=True) overview = CharField(max_length=100) detailed = CharField(max_length=300, blank=True, null=True) phone_number = IntegerField(blank=True, null=True) email_address = EmailField(blank=True, null=True) rating = IntegerField(default=0) price = IntegerField(default=0) picture = models.ImageField(upload_to='images/', null=True) lat = FloatField(default=55.8642) lng = FloatField(default=-4.2518) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Restaurant, self).save(*args, **kwargs) def __str__(self): return self.name
class Member(models.Model): # num 필드 설정 ( 자동 증가되는 primary key 값 ) num = AutoField(primary_key=True) # name 필드 설정 ( 최대 길이 : 30, null 허용하지 않음 ) name = CharField(max_length=30, null=False) # addr 필드 설정 ( 최대 길이 : 50, null 허용) addr = CharField(max_length=50, null=True)
class _ModelWithIntPKABC(_ModelWithObjectsManagerAndDefaultMetaOptionsABC): # docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields # docs.djangoproject.com/en/dev/ref/models/fields/#autofield id: AutoField = \ AutoField( verbose_name='Integer Primary Key', help_text='Integer Primary Key', null=False, blank=False, choices=None, db_column=None, db_index=True, db_tablespace=None, default=None, editable=False, # error_messages={}, primary_key=True, unique=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, # validators=() ) class Meta(_ModelWithObjectsManagerAndDefaultMetaOptionsABC.Meta): # pylint: disable=too-few-public-methods """Metadata.""" abstract = True
class Modul(models.Model): """ Modul er en 'time' eller lektion, der er/bliver `afholdt` på en bestemt dag som del af et Forløb. """ id = AutoField(primary_key=True, verbose_name='Modul-løbenummer (automatisk)') forløb = ForeignKey('Forløb', on_delete=models.RESTRICT, null=True) oprettet = models.DateTimeField( #default=timezone.now() auto_now_add= True, # https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now_add ) opdateret = models.DateTimeField( # NB: Dato odateres ved Model.save() ikke ved QuerySet.update(), se dokumenation! #default=timezone.now(), auto_now= True, # https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now ) afholdt = DateField(help_text='Planlagt / faktisk dato for modulet') class Meta: ordering = ['afholdt', 'id'] verbose_name_plural = 'moduler' def __str__(self): return f"Modul {self.id} '{self.forløb.titel}', {self.afholdt} ({self.forløb.klasse})." def get_absolute_url(self): """Returnerer URL, der tilgår et bestemt Modul.""" return reverse('modul_tildel', args=[str(self.id)])
def _prepare(self, model): from django.db import connection from django.db.backends.util import truncate_name if self.order_with_respect_to: self.order_with_respect_to = self.get_field( self.order_with_respect_to) self.ordering = ('_order', ) else: self.order_with_respect_to = None if self.pk is None: if self.parents: # Promote the first parent link in lieu of adding yet another # field. field = self.parents.value_for_index(0) field.primary_key = True self.setup_pk(field) else: auto = AutoField(verbose_name='ID', primary_key=True, auto_created=True) model.add_to_class('id', auto) # If the db_table wasn't provided, use the app_label + module_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.module_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
def _prepare(self, model): if self.order_with_respect_to: self.order_with_respect_to = self.get_field( self.order_with_respect_to) self.ordering = ('_order', ) model.add_to_class('_order', OrderWrt()) else: self.order_with_respect_to = None if self.pk is None: if self.parents: # Promote the first parent link in lieu of adding yet another # field. field = next(six.itervalues(self.parents)) # Look for a local field with the same name as the # first parent link. If a local field has already been # created, use it instead of promoting the parent already_created = [ fld for fld in self.local_fields if fld.name == field.name ] if already_created: field = already_created[0] field.primary_key = True self.setup_pk(field) else: auto = AutoField(verbose_name='ID', primary_key=True, auto_created=True) model.add_to_class('id', auto)
def test_convert_values_to_handle_null_value(self): database_operations = DatabaseOperations(connection) self.assertEqual( None, database_operations.convert_values(None, AutoField(primary_key=True)) ) self.assertEqual( None, database_operations.convert_values(None, DateField()) ) self.assertEqual( None, database_operations.convert_values(None, DateTimeField()) ) self.assertEqual( None, database_operations.convert_values(None, DecimalField()) ) self.assertEqual( None, database_operations.convert_values(None, IntegerField()) ) self.assertEqual( None, database_operations.convert_values(None, TimeField()) )
class Member(models.Model): # 자동증가 되는 숫자 , primary key num=AutoField(primary_key=True) # 문자 최대 30자 null 허용 하지 않음 name=CharField(max_length=30, null=False) # 문자 최대 30자 null 허용 addr=CharField(max_length=50, null=True)
def _prepare(self, model): if self.order_with_respect_to: # The app registry will not be ready at this point, so we cannot # use get_field(). query = self.order_with_respect_to try: self.order_with_respect_to = next( f for f in self._get_fields(reverse=False) if f.name == query or f.attname == query ) except StopIteration: raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, query)) self.ordering = ('_order',) if not any(isinstance(field, OrderWrt) for field in model._meta.local_fields): model.add_to_class('_order', OrderWrt()) else: self.order_with_respect_to = None if self.pk is None: if self.parents: # Promote the first parent link in lieu of adding yet another # field. field = next(iter(self.parents.values())) # Look for a local field with the same name as the # first parent link. If a local field has already been # created, use it instead of promoting the parent already_created = [fld for fld in self.local_fields if fld.name == field.name] if already_created: field = already_created[0] field.primary_key = True self.setup_pk(field) else: auto = AutoField(verbose_name='ID', primary_key=True, auto_created=True) model.add_to_class('id', auto)
class TeacherAchievement(models.Model): id = AutoField(primary_key=True) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) achievement = models.ForeignKey(Achievement, on_delete=models.CASCADE) class Meta: db_table = "teacher_achievement"
def test_autofield_not_spanner_w_default(self): """Not Spanner, default provided.""" connection.settings_dict["ENGINE"] = "another_db" mock_func = mock.Mock() field = AutoField(name="field_name", default=mock_func) assert gen_rand_int64 != field.default assert mock_func == field.default connection.settings_dict["ENGINE"] = "django_spanner"
def test_convert_values_to_handle_null_value(self): from django.db.backends.sqlite3.base import DatabaseOperations convert_values = DatabaseOperations(connection).convert_values self.assertIsNone(convert_values(None, AutoField(primary_key=True))) self.assertIsNone(convert_values(None, DateField())) self.assertIsNone(convert_values(None, DateTimeField())) self.assertIsNone(convert_values(None, DecimalField())) self.assertIsNone(convert_values(None, IntegerField())) self.assertIsNone(convert_values(None, TimeField()))
class TeachingInfo(models.Model): id = AutoField(primary_key=True) school_year = models.CharField(max_length=250) semester = models.SmallIntegerField() teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) class Meta: db_table = "teaching_information"
class CONDITION_ERA(models.Model): condition_era_id = AutoField(primary_key=True) person = models.ForeignKey(PERSON, on_delete=models.DO_NOTHING, related_name="condition_era") condition_concept = models.ForeignKey(CONCEPT, on_delete=models.DO_NOTHING, limit_choices_to=Q(domain__domain_id='Condition'), related_name="+") condition_era_start_date = models.DateTimeField() condition_era_end_date = models.DateTimeField() condition_occurrence_count = models.IntegerField(null=True) class Meta: db_table = "CONDITION_ERA"
class Comment(models.Model): review_ID = AutoField(primary_key=True) user = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) date_time = models.DateTimeField(null=True) comment = CharField(max_length=1000) rating = IntegerField() price = IntegerField() def __str__(self): return self.user.username + ", " + self.restaurant.name
def copy_fields(model): """ Creates copies of the model's original fields, returning a dictionary mapping field name to copied field object. """ fields = { PK: AutoField(verbose_name=PK, primary_key=True, auto_created=True), CU: create_user_field(CU), DU: create_user_field(DU), VF: DecimalField(max_digits=18, decimal_places=6, default=0, auto_created=True), VU: DecimalField(max_digits=18, decimal_places=6, default=MAX, auto_created=True)} for field in model._meta.local_fields: if field.name in FORBIDDEN_FIELDS: raise Exception('Can not use `%s` as a field name ' 'with django-timetravel') _field = get_non_related(field) _field.primary_key = field.primary_key if isinstance(_field, AutoField): _field = auto_to_integer(field) _field._tt_field_attrname = field.attname _field._tt_field_name = field.name if not isinstance(_field, BooleanField): _field.null = True if _field.primary_key: _field.primary_key = False _field.serialize = True _field.name = OK _field.db_index = True _field.null = False _field.db_column = field.db_column or field.attname _field._unique = False _field.unique_for_date = False if _field.unique_for_date else None _field.unique_for_month = False if _field.unique_for_month else None _field.unique_for_year = False if _field.unique_for_year else None _field.auto_now = False _field.auto_now_add = False _field.auto_created = False fields[_field.name] = _field return fields
def _prepare(self, model): # 排序的属性 if self.order_with_respect_to: self.order_with_respect_to = self.get_field(self.order_with_respect_to) self.ordering = ('_order',) model.add_to_class('_order', OrderWrt()) else: self.order_with_respect_to = None if self.pk is None: if self.parents: # Promote 促进, 提升 the first parent link in lieu of adding yet another # field. field = next(six.itervalues(self.parents)) # Look for a local field with the same name as the # first parent link. If a local field has already been # created, use it instead of promoting the parent already_created = [fld for fld in self.local_fields if fld.name == field.name] if already_created: field = already_created[0] field.primary_key = True self.setup_pk(field) else: auto = AutoField(verbose_name='ID', primary_key=True, auto_created=True) model.add_to_class('id', auto) # 如果两个属性同时关联两个外部表, 比如两个外键的时候, 需要创建一个集合. # Determine any sets of fields that are pointing to the same targets # (e.g. two ForeignKeys to the same remote model). The query # construction code needs to know this. At the end of this, # self.duplicate_targets will map each duplicate field column to the # columns it duplicates. collections = {} for column, target in six.iteritems(self.duplicate_targets): try: collections[target].add(column) except KeyError: collections[target] = set([column]) self.duplicate_targets = {} for elt in six.itervalues(collections): if len(elt) == 1: continue for column in elt: # elt_set - set([column]) self.duplicate_targets[column] = elt.difference(set([column]))
def get_history_id_field(self, model): """Return a field instance without initially assuming it should be AutoField. For example, primary key is UUIDField( primary_key=True, default=uuid.uuid4). """ try: field = [ field for field in model._meta.fields if field.primary_key][0] field = field.__class__(primary_key=True, default=field.default) except (IndexError, TypeError): field = AutoField(primary_key=True) return field
class Emne(models.Model): """Faglige emner, som danner rammen om forløb for de enkelte klasser""" id = AutoField(primary_key=True, verbose_name='Emne-løbenummer (automatisk)') titel = CharField(max_length=20, help_text='Betegnelse for emnet') oprettet = models.DateTimeField( #default=timezone.now() auto_now_add= True, # https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now_add ) opdateret = models.DateTimeField( # NB: Dato odateres ved Model.save() ikke ved QuerySet.update(), se dokumenation! #default=timezone.now(), # auto_now= True, # https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now ) f*g = CharField( # Eller ForeignKey til (ikke oprettet) Model: F*g. max_length=3, choices=[('mat', 'Matematik'), ('it', 'Informationsteknologi')], default='Matematik') studieretning = CharField(max_length=3, choices=[('stx', 'STX'), ('hf', 'HF'), ('htx', 'HTX'), ('hhx', 'HHX'), ('eux', 'EUX'), ('eud', 'EUD'), ('etc', 'Andet')], default='stx', help_text='Klassens studieretning') faglige_mål = TextField( max_length=1000, help_text='Bekendtgørelsens og skolens faggruppes krav til emnet') note = TextField(max_length=1000, null=True, blank=True, help_text='Lærerens krav til og ambitioner for emnet') klassetrin = IntegerField( validators=[MinValueValidator(1), MaxValueValidator(4)], help_text='Årgang, emnet undervises på (siden holdets startår)', ) varighed = IntegerField(help_text='Forventet antal lektioner/moduler') class Meta: ordering = ['f*g', 'studieretning', 'klassetrin', 'titel'] verbose_name_plural = 'emner' def __str__(self): return f"{self.f*g}-{self.studieretning}/{self.klassetrin}: {self.titel}. " def get_absolute_url(self): """Returnerer URL, der tilgår en bestemt instantiering af Emne.""" return reverse('emne-detalje-visning', args=[str(self.id)])
def _prepare(self, model): if self.order_with_respect_to: self.order_with_respect_to = self.get_field( self.order_with_respect_to) self.ordering = ('_order', ) else: self.order_with_respect_to = None if self.pk is None: auto = AutoField(verbose_name='ID', primary_key=True) auto.creation_counter = -1 model.add_to_class('id', auto) # If the db_table wasn't provided, use the app_label + module_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.module_name)
class Borrower(models.Model): idborrower = AutoField(primary_key=True) name = models.CharField(max_length=128) phone = models.CharField(max_length=10) email = models.EmailField(null=True, blank=True, default=None) #some do not have/use email cellgroup = models.CharField(max_length=128) statusflag = models.CharField( max_length=16, choices=(('NM', 'Normal'), ('SP', 'Special')), default='NM') #this should only be changed in admin view objects = models.Manager() # The default manager. idle_borrowers = BorrowerManager() def get_borrower_status(self): """ Get status of a borrower. """ if self.statusflag == 'NM': # is the book in normal status (not lost/reserved etc.) q = Transaction.objects.filter( borrower=self, return_date=None) #is this user currently borrowing a book? if q.exists(): if q[0].is_overdue(): return 'Overdue' else: return 'Borrowing' else: return 'Idle' else: return 'Reserved' get_borrower_status.short_description = 'Status' def get_times_overdue(self): q = Transaction.overdued_transactions.filter(borrower=self) return len(q) get_times_overdue.short_description = 'Times overdue' def __str__(self): return self.name class Meta: unique_together = ('name', 'phone') ordering = ["name"]
def _prepare(self, model): if self.order_with_respect_to: self.order_with_respect_to = self.get_field( self.order_with_respect_to) self.ordering = ('_order', ) else: self.order_with_respect_to = None # Now we initialize the primary key. for field_name in self._primary_key: self.pk.append(self.get_field(field_name)) del self._primary_key if not self.pk: if self.parents: # Promote the first parent link in lieu of adding yet another # field. field = self.parents.value_for_index(0) field.primary_key = True self.setup_pk(field) else: auto = AutoField(verbose_name='ID', primary_key=True, auto_created=True) model.add_to_class('id', auto) # Determine any sets of fields that are pointing to the same targets # (e.g. two ForeignKeys to the same remote model). The query # construction code needs to know this. At the end of this, # self.duplicate_targets will map each duplicate field column to the # columns it duplicates. collections = {} for column, target in self.duplicate_targets.iteritems(): try: collections[target].add(column) except KeyError: collections[target] = set([column]) self.duplicate_targets = {} for elt in collections.itervalues(): if len(elt) == 1: continue for column in elt: self.duplicate_targets[column] = elt.difference(set([column]))
def _prepare(self, model): from django.db import connection from django.db.backends.util import truncate_name if self.order_with_respect_to: self.order_with_respect_to = self.get_field( self.order_with_respect_to) self.ordering = ('_order', ) else: self.order_with_respect_to = None if self.pk is None: auto = AutoField(verbose_name='ID', primary_key=True) auto.creation_counter = -1 model.add_to_class('id', auto) # If the db_table wasn't provided, use the app_label + module_name. if not self.db_table: self.db_table = "%s_%s" % (self.app_label, self.module_name) self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
class Forløb(models.Model): """Forløb er et Emne, der gennemgås i en Klasse fra et bestemt tidspunkt (`påbegyndt`) og som har en planlagt `varighed`.""" id = AutoField(primary_key=True, verbose_name='Forløbs-løbenummer (automatisk)') emne = ForeignKey('Emne', on_delete=models.RESTRICT, null=True) klasse = ForeignKey('Klasse', on_delete=models.RESTRICT, null=True) oprettet = models.DateTimeField( #default=timezone.now() auto_now_add= True, # https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now_add ) opdateret = models.DateTimeField( # NB: Dato odateres ved Model.save() ikke ved QuerySet.update(), se dokumenation! #default=timezone.now(), auto_now= True, # https://docs.djangoproject.com/en/3.2/ref/models/fields/#django.db.models.DateField.auto_now ) titel = CharField(max_length=20, help_text='Overskrift for forløbet') påbegyndt = DateField(help_text='Dato for planlagt start af forløbet') varighed = IntegerField(help_text='Forventet antal lektioner/moduler') kommentar = TextField( max_length=500, null=True, blank=True, help_text= 'Præsentation til holdets elever af det konkrete forløb i klassen') class Meta: ordering = ['klasse', 'emne'] verbose_name_plural = 'forløb' def __str__(self): return f"{self.klasse.kortnavn}: fra {self.påbegyndt} -- {self.emne}" def get_absolute_url(self): """Returnerer URL, der tilgår et bestemt Forløb.""" return reverse('forloeb-detalje-visning', args=[str(self.id)])
class _ModelWithIntPKMixInABC(Model): # https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields id = AutoField( # https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.AutoField null=False, blank=False, choices=None, db_column=None, db_index=True, db_tablespace=None, default=None, editable=False, # error_messages=None, help_text='Integer Primary Key', primary_key=True, unique=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, verbose_name='Integer Primary Key', # validators=() # must be iterable ) class Meta: abstract = True
def test_AutoField(self): lazy_func = lazy(lambda: 1, int) self.assertIsInstance( AutoField(primary_key=True).get_prep_value(lazy_func()), int)
def test_AutoField(self): self.assertIsInstance( AutoField(primary_key=True).get_prep_value(1), int)
def test_autofield_not_spanner(self): """Not Spanner, default not provided.""" connection.settings_dict["ENGINE"] = "another_db" field = AutoField(name="field_name") assert gen_rand_int64 != field.default connection.settings_dict["ENGINE"] = "django_spanner"
def test_autofield_default(self): """Spanner, default provided.""" mock_func = mock.Mock() field = AutoField(name="field_name", default=mock_func) assert gen_rand_int64 != field.default assert mock_func == field.default
def test_autofield_no_default(self): """Spanner, default is not provided.""" field = AutoField(name="field_name") assert gen_rand_int64 == field.default