Python Web Development Skills VI

What does "#noqa" mean

# noqa is a special comment used to tell some of Python's code quality inspection tools (eg: flake8, pylint, etc.) to ignore certain rule checks for the current line. noqa It is an acronym for "No Quality Assurance".

for example:

(1) If you have a line of code that exceeds the limit of code inspection tools (usually 80 or 120 characters), but you think it is reasonable, you can add a comment at the end of the # noqaline

url = https://www.baidu.com?user_info=hahhahahaahahahahahahahahahahahahahahahahhahahh  # noqa

(2)import *

from apps import *  # noqa

# type: ignore what is the use

# type: ignoreis a special annotation used to tell the Python type checker (like mypy) to ignore type errors for the current line

One more key is bound to the database table, the type is a string, with a default value, is it compatible with the original data?

able.

django models set joint index

Understand at a glance:

from django.db import models
from django.db.models import Index

class MyModel(models.Model):
    field1 = models.CharField(max_length=100)
    field2 = models.CharField(max_length=100)
    field3 = models.CharField(max_length=100)

    class Meta:
        indexes = [
            Index(fields=['field1', 'field2'], name='field1_field2_idx'),
        ]

When to consider using uuid in table design

When designing a database table, consider using UUID ( Universal Unique Identification Code ) as the primary key or unique identifier. Condition:

  1. Distributed system: When your application or system needs to synchronize and share data among multiple servers, databases or data centers, UUID ensures that each record has a unique identifier in the entire system, helping to avoid primary key conflicts and The data is inconsistent .

  2. Data merging : When data from different sources needs to be merged into one table, using UUID can ensure that each record has a unique identifier and avoid primary key conflicts .

  3. Unique security : UUID is random and not easy to predict, which helps to improve data security. UUIDs can be used when you don't want users to be able to predict the primary key value of a record.

  4. Create records offline: In some scenarios, the client may need to create records offline, and then synchronize to the server when the network connection is restored. Using UUID as the primary key ensures that records created offline will not conflict with records on the server when syncing.

There are also some disadvantages, such as a larger storage space and possibly lower query performance . Please weigh these pros and cons when using UUIDs.

The related_name function of Django models

Used to define the name of a back-relation. When you define a foreign key (ForeignKey), one-to-one relationship (OneToOneField) or many-to-many relationship (ManyToManyField) in the model, you can use to related_namecustomize the property name to access the source object from the related object.

related_nameThe main uses of are:

  1. Provides a more readable name for the reverse association, making the code more maintainable.
  2. Resolve naming conflicts that may arise when defining relationships.
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='books')

When we fetch an Authorinstance, author.booksall books associated with that author can be accessed by (if not set related_name, the default reverse association name will be book_set, in which case you need to access author.book_setthe associated books with ).

Add a foreign key to the migrated database table, and set the name value of the original table to the default value

Test the feasible solution:
After makemigrations, modify the migration file.

class Migration(migrations.Migration):

    dependencies = [
        ('ormtest', '0016_remove_passwordmodel_charmodel'),
    ]

    operations = [
        migrations.AddField(
            model_name='passwordmodel',
            name='charmodel',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='passwordModel', to='ormtest.CharModel', verbose_name='主题'),
        ),
    ]

Modified to (add migrations.RunPython(set_default_charmodel) and set_default_charmodel methods)

def set_default_charmodel(apps, schema_editor):
    PasswordModel = apps.get_model('ormtest', 'PasswordModel')
    CharModel = apps.get_model('ormtest', 'CharModel')

    for password_model in PasswordModel.objects.all():
        char_model, _ = CharModel.objects.get_or_create(name=password_model.password)  
        password_model.charmodel = char_model 
        password_model.save()


class Migration(migrations.Migration):

    dependencies = [
        ('ormtest', '0016_remove_passwordmodel_charmodel'),
    ]

    operations = [
        migrations.AddField(
            model_name='passwordmodel',
            name='charmodel',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='passwordModel', to='ormtest.CharModel', verbose_name='主题'),
        ),
        migrations.RunPython(set_default_charmodel),
    ]

Then migrate.

Guess you like

Origin blog.csdn.net/lxd_max/article/details/131924659