Ошибка типа: преобразование из десятичного поля в десятичное не поддерживается

#python-3.x #django #django-models #django-views #django-forms

Вопрос:

Я создаю веб-сайт торгов с использованием Django. Я обнаружил проблему в models.py . Я не могу выполнить команду оболочки migrate и не знаю почему. Может ли кто-нибудь помочь в этом? Заранее спасибо.

models.py как показано ниже:

 class User(AbstractUser):
    pass

    def __str__(self):
        return f"{self.username}"

class AuctionItem(models.Model):
    '''
    Description of Auction Item
    '''

    category_choices = [
        ("Fa", "Fashion"),
        ("To", "Toys"),
        ("Fo", "Food"),
        ("El", "Electronics"),
        ("Ho", "Home")
    ]

    title = models.CharField(max_length=16)
    description = models.CharField(max_length=128)
    image = models.URLField()
    category = models.CharField(max_length=16, choices=category_choices)
    create_time = models.DateTimeField(auto_now_add=True)
    seller = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="owned")
    initial_price = models.DecimalField(max_digits=10, decimal_places=2, null=True)
    current_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, default=0)

class BiddingPrice(models.Model):
    '''
    Bidding price of each item
    '''
    bid_price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    bidder = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    auction_item = models.ForeignKey(AuctionItem, on_delete=models.CASCADE, null=True, related_name="bidding_price")

class Comments(models.Model):
    '''
    Comments made by different users
    '''
    comments = models.CharField(max_length=200)
    commentor = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="comments_given")
    connected_item = models.ManyToManyField(AuctionItem)
 

Сообщение об ошибке выглядит так:

 commerce % python manage.py migrate       
Operations to perform:
  Apply all migrations: admin, auctions, auth, contenttypes, sessions
Running migrations:
  Applying auctions.0006_auto_20210718_0731...Traceback (most recent call last):
  File "/Users/huanwang/Documents/cs_courses/cs50/web50/projects/2020/x/commerce/manage.py", line 21, in <module>
    main()
  File "/Users/huanwang/Documents/cs_courses/cs50/web50/projects/2020/x/commerce/manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/core/management/base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/core/management/base.py", line 369, in execute
    output = self.handle(*args, **options)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 231, in handle
    post_migrate_state = executor.migrate(
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/db/migrations/migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 110, in database_forwards
    schema_editor.add_field(
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 328, in add_field
    self._remake_table(model, create_field=field)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 189, in _remake_table
    self.effective_default(create_field)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 303, in effective_default
    return field.get_db_prep_save(self._effective_default(field), self.connection)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 1510, in get_db_prep_save
    return connection.ops.adapt_decimalfield_value(self.to_python(value), self.max_digits, self.decimal_places)
  File "/usr/local/Caskroom/miniconda/base/envs/web_programming/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 1501, in to_python
    return decimal.Decimal(value)
TypeError: conversion from DecimalField to Decimal is not supported
 

Комментарии:

1. Можете ли вы попробовать изменить значения по умолчанию на Decimal('0.00') . Если это не сработает, можете ли вы поделиться всей обратной связью? Не забывай from decimal import Decimal

2. Я пробовал, но это все равно не работает. Пожалуйста, найдите весь трек, как показано ниже.

3. Вы воссоздали миграции?

4. ДА… Я сделал это…

5. Я удалил все файлы миграции, и проблема исчезла. Большое вам спасибо!! Это беспокоит меня 2 дня.

Ответ №1:

Измененный код выглядит следующим образом и. После того, как я удалил все предыдущие файлы миграции и запустил ее снова. Это работает.

 from django.contrib.auth.models import AbstractUser
from django.db import models
from decimal import Decimal

class User(AbstractUser):
    pass

    def __str__(self):
        return f"{self.username}"

class AuctionItem(models.Model):
    '''
    Description of Auction Item
    '''

    category_choices = [
        ("Fa", "Fashion"),
        ("To", "Toys"),
        ("Fo", "Food"),
        ("El", "Electronics"),
        ("Ho", "Home")
    ]

    title = models.CharField(max_length=16)
    description = models.CharField(max_length=128)
    image = models.URLField()
    category = models.CharField(max_length=16, choices=category_choices)
    create_time = models.DateTimeField(auto_now_add=True)
    seller = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="owned")
    initial_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, default=Decimal("0.00"))
    current_price = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal("0.00"))

class BiddingPrice(models.Model):
    '''
    Bidding price of each item
    '''
    bid_price = models.DecimalField(max_digits=10, decimal_places=2, default=Decimal("0.00"))
    bidder = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    auction_item = models.ForeignKey(AuctionItem, on_delete=models.CASCADE, null=True, related_name="bidding_price")


class Comments(models.Model):

    comments = models.CharField(max_length=200)
    commentor = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name="comments_given")
    connected_item = models.ManyToManyField(AuctionItem)