程序设计应用2023-04-08 week6

visual studio code里面可以安装docker插件

new dev container

 

 

db_index=true普通索引

unique=true唯一索引

class Meta:

    indexes=[]

    unique_together

 

python manage.py makemigrations  现根据类生成迁移脚本

python manage.py migrate  打脚本

 

在models里面定义索引

from django.db import models

class MyModel(models.Model):
    my_field = models.CharField(max_length=100, db_index=True, unique=True)
    # Other fields and model definitions go here

By setting db_index=True, Django will create an index for the my_field field in the database, improving the performance of queries that involve this field.

 

 

In Django, the Meta class is used to define metadata options for a model. It allows you to provide additional information about the model that is not a field, such as ordering, database table name, verbose names, and more.

The Meta class is an inner class defined within a Django model class. By convention, it is named Meta and is defined directly after the model fields. Here's an example:

from django.db import models

class MyModel(models.Model):
    # model fields go here

    class Meta:
        verbose_name = "My Model"
        ordering = ['field1', '-field2']

In this example, Meta is used to define metadata options for the MyModel class. verbose_name specifies a human-readable name for the model, which can be used in various places such as the Django admin interface. ordering specifies the default ordering of query results when retrieving objects of this model.

There are several other options you can define in the Meta class, such as db_table to specify a custom database table name, unique_together to define unique constraints on multiple fields, indexes to define custom indexes, and more. These options allow you to customize the behavior and presentation of your Django models.

Overall, the Meta class provides a way to specify various metadata and configuration options for a model in Django.

 

Here's an example of how to define a combined index using the Meta class in Django:

from django.db import models

class MyModel(models.Model):
    field1 = models.CharField(max_length=50)
    field2 = models.IntegerField()
    field3 = models.DateField()

    class Meta:
        indexes = [
            models.Index(fields=['field1', 'field2']),
            models.Index(fields=['field2', 'field3'], name='custom_index_name'),
        ]

In this example, we have a MyModel class with three fields: field1, field2, and field3. Within the Meta class, we define the indexes attribute as a list of Index instances.

The first index specifies a combined index on field1 and field2 using the fields parameter. This means that the database will create an index that considers both field1 and field2 together.

The second index demonstrates a combined index on field2 and field3, but with a custom name specified using the name parameter.

By defining combined indexes, you can optimize queries that involve multiple fields together. The order of fields in the index definition can also impact the index's effectiveness, so consider the query patterns of your application when defining combined indexes.

 

The unique_together attribute in the Meta class allows you to specify combinations of fields that should be unique together in the database. This means that the combination of values for the specified fields must be unique for each record in the table. Here's an example of how to use unique_together:

from django.db import models

class MyModel(models.Model):
    field1 = models.CharField(max_length=50)
    field2 = models.IntegerField()
    field3 = models.DateField()

    class Meta:
        unique_together = [['field1', 'field2']]

In this example, we have a MyModel class with three fields: field1, field2, and field3. The Meta class contains the unique_together attribute, which is set to a list of lists. Each inner list represents a unique constraint on a combination of fields. In this case, we specify that field1 and field2 should be unique together.

By defining unique_together, Django will create a database constraint that ensures the combination of values for field1 and field2 is unique for each record in the table. If an attempt is made to save a record with a duplicate combination, Django will raise a validation error.

You can specify multiple combinations of fields using multiple inner lists within unique_together. For example:

class MyModel(models.Model):
    field1 = models.CharField(max_length=50)
    field2 = models.IntegerField()
    field3 = models.DateField()

    class Meta:
        unique_together = [
            ['field1', 'field2'],
            ['field2', 'field3'],
        ]

In this case, both the combinations of field1 and field2, and field2 and field3 must be unique.

 

Note: As of Django 2.2, the unique_together option is considered obsolete and the current recommendation is to use the UniqueConstraint instead. The UniqueConstraint provides more functionality than unique_together, such as the ability to specify a name for the constraint.

I still use unique_together, even though it is considered obsolete. There are a few reasons for this:

  • unique_together is more concise and easier to read than UniqueConstraint.
  • unique_together is supported by older versions of Django.
  • unique_together is used by the Django admin, so it is easier to use for models that are used in the admin.

However, I am aware that unique_together is not as flexible as UniqueConstraint. If I need to do something that unique_together cannot do, I will use UniqueConstraint instead.

 

 

特殊查询表达式,

f表达式

d.yw=F('yw')+10  在save的时候会把value算出来

d.refresh_from_db()

 

F表达式课比较一行数据的2个列是否相等

filter(yw=F('sx'))

 

django annotate  在class上面,增加属性

django.db.models.functions.Left 

__gt=

 

aggregate(Avg('w'))

 

RawSQLD使用

 

If you have a CharField with max_length=200 and you store the values 'hello' and 'abc' in that field, the actual length occupied in the database will be the length of the stored value itself, not the maximum length specified in the field.

In this case, 'hello' will occupy 5 characters and 'abc' will occupy 3 characters in the database. The max_length parameter in the CharField is used for validation and to set the maximum allowed length for the field's value. It does not determine the storage size in the database.

Django will automatically truncate any value longer than the specified max_length when saving it to the database, or raise an error if the max_length constraint is violated.

 

The F expression in Django allows you to reference a database column's value and perform database-level operations or comparisons with it. It represents a column or a value in the database and allows you to perform operations on it without fetching the data into Python.

The F expression is useful in scenarios where you want to update or filter the queryset based on the value of a specific column. It allows you to perform operations like addition, subtraction, multiplication, division, and more on the column values directly at the database level.

Here's an example to illustrate how F expression works:

from django.db.models import F

# Increase the value of 'views' column by 1 for all instances
Model.objects.all().update(views=F('views') + 1)

# Filter instances where 'quantity' is greater than 'price'
Model.objects.filter(quantity__gt=F('price'))

# Perform complex calculations on columns
Model.objects.filter(total_price=F('quantity') * F('price') + F('discount'))

In the examples above, F('column_name') represents the value of the specified column in the database. You can use F expressions in various database operations like filters, updates, annotations, and aggregations to perform efficient and accurate calculations or comparisons at the database level. 

 

 

 

posted @ 2023-04-08 10:15  ChuckLu  阅读(11)  评论(0编辑  收藏  举报