运行django测试会导致重复的列名ID

时间:2019-02-19 12:53:22

标签: python mysql django testing

我正在创建一个测试以测试Django中的辅助函数。运行测试时,出现错误“重复的列名称ID”

我尝试运行python3 manage.py migrate --fake-initial,在Stackoverflow上看到了一个解决方案,说明它可以工作,但是没有。

Test.py

from django.test import TestCase
from reservations.models import Reservation, Table, Restaurant
from employee.helpers import *


class GetTablesWithCapacityTestCase(TestCase):
    def setUp(self):
        Restaurant.objects.create(
            name="Test Restaurant",
            description="Restaurant for use in test",
            opening_time=12,
            closing_time=24,
        )
        Table.objects.create(
            restaurant=Restaurant.objects.filter(name="Test Restaurant"),
            number_of_seats=5,
            is_occupied=0
        )
        Table.objects.create(
            restaurant=Restaurant.objects.filter(name="Test Restaurant"),
            number_of_seats=4,
            is_occupied=0
        )

    def test_get_tables(self):
        tables = get_tables_with_capacity(5)
        self.assertEqual(1, tables.size)

Models.py:

from django.db import models
from guest.models import Guest
from django.utils import timezone


class Restaurant(models.Model):
    name = models.CharField(max_length=250)
    description = models.CharField(max_length=250)
    opening_time = models.TimeField()
    closing_time = models.TimeField()

    def __str__(self):
        return self.name


class Table(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True, blank=True)
    number_of_seats = models.IntegerField()
    is_occupied = models.BooleanField()

    def __str__(self):
        return str(self.id)


class Reservation(models.Model):
    guest = models.ForeignKey(Guest, on_delete=models.CASCADE)
    number_of_people = models.IntegerField(default=0)
    start_date_time = models.DateTimeField(default=timezone.now)
    end_date_time = models.DateTimeField(default=timezone.now)
    created_date = models.DateTimeField(default=timezone.now)
    table = models.ForeignKey(Table, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.start_date_time

编辑2: Guest.models:

class Guest(models.Model):
    email = models.EmailField()
    reminder = models.BooleanField()

    def __str__(self):
        return self.email

运行测试时得到的结果是:

MySQLdb._exceptions.OperationalError: (1060, "Duplicate column name 'table_id'")

The above exception was the direct cause of the following exception:

django.db.utils.OperationalError: (1060, "Duplicate column name 'table_id'")

编辑1: 完整的堆栈跟踪: What's out of the picture is "Got an error creating the test database: (1007, "Can't create database 'test_stud_pu-29_trippinTacos'; database exists")"

是的,我使用的是MySQL,而不是内置的Django SQLite。

我显然希望输出是失败的测试或成功的测试。

希望有人可以提供帮助!

1 个答案:

答案 0 :(得分:0)

已修复

我删除了所有迁移文件,然后运行python3 manage.py makemigrations。这样就解决了。