Why does Django make migrations for help_text and verbose_name changes?

后端 未结 8 2271
情深已故
情深已故 2020-12-15 15:00

When I change help_text or verbose_name for any of my model fields and run python manage.py makemigrations, it detects these changes a

相关标签:
8条回答
  • 2020-12-15 15:50

    To avoid unnecessary migrations You can do as follows:

    1. Subclass field that causes migration
    2. Write custom deconstruct method inside that field
    3. Profit

    Example:

    from django.db import models
    
    class CustomCharField(models.CharField):  # or any other field
    
        def deconstruct(self):
            name, path, args, kwargs = super(CustomCharField, self).deconstruct()
            # exclude all fields you dont want to cause migration, my example below:
            if 'help_text' in kwargs:
                del kwargs['help_text']
            if 'verbose_name' in kwargs:
                del kwargs['verbose_name']
            return name, path, args, kwargs
    

    Hope that helps

    0 讨论(0)
  • 2020-12-15 15:53

    I have written custom module for that purpose

    All you need is to save it in some utils/models.db and in all your models instead of from django.db import models write from utils import models

    If somebody is interested in it I can write a component and publish it on pypi

    UPD: try this https://github.com/FeroxTL/django-migration-control

    # models.py

    # -*- coding: utf-8 -*-
    from types import FunctionType
    from django.db import models
    
    
    class NoMigrateMixin(object):
        """
        Позволяет исключить из миграций различные поля
        """
        def deconstruct(self):
            name, path, args, kwargs = super(NoMigrateMixin, self).deconstruct()
            kwargs.pop('help_text', None)
            kwargs.pop('verbose_name', None)
            return name, path, args, kwargs
    
    
    # =============================================================================
    # DJANGO CLASSES
    # =============================================================================
    
    for name, cls in models.__dict__.items():
        if isinstance(cls, type):
            if issubclass(cls, models.Field):
                # Поля
                globals()[name] = type(name, (NoMigrateMixin, cls), {})
            else:
                # Всякие менеджеры
                globals()[name] = cls
        elif isinstance(cls, FunctionType):
            # Прочие функции
            globals()[name] = cls
    
    0 讨论(0)
提交回复
热议问题