Django不会在数据库中创建对象

时间:2018-04-11 15:18:00

标签: python django postgresql

我不确定是什么问题 我尝试过迁移/ makemigrations,但没有帮助,我在virtualenv tho工作 我的models.py

    from django.db import models
import re


# Create your models here.
class Currency(models.Model):
    def __str__(self):
        return self.short
    name = models.CharField(max_length=32, null=True, blank=True)
    country = models.CharField(max_length=50, null=True, blank=True)
    short = models.CharField(max_length=10, null=True, blank=True)


class Source(models.Model):
    def __str__(self):
        return self.name + '({}...)'.format(self.url[:20])
    url = models.URLField()
    name = models.CharField(max_length=250, verbose_name='Source_name')
    timestamp = models.DateTimeField(auto_now_add=True)
    currency = models.ForeignKey(Currency)

    def save(self, *args, **kwargs):
        self.name = ''.join(re.sub('\s+', ' ', self.name).strip())
        super(Source, self).save()


class Product(models.Model):
    def __str__(self):
        return self.name
    name = models.CharField(max_length=250, blank=False)
    prices = models.ManyToManyField(to='Price', blank=True)
    date_creation = models.DateField(auto_now_add=True)
    prod_code = models.CharField(max_length=250, blank=True, null=True)

    def save(self, *args, **kwargs):
        self.name = ''.join(re.sub('\s+', ' ', self.name).strip())
        super(Product, self).save()  

我创建对象的函数

def from_csv_to_db(csv_name):  # empty DB
try:
    df = pd.read_csv(csv_name, sep=';')
except FileNotFoundError:
    return ('Please input correct path to csv file or check spelling. Process finished')
for i, row in df.iterrows():
    Currency.objects.get_or_create(short=row['source__currency__short'], id=row['source__currency_id'])
    Product.objects.get_or_create(id=row['product__id'], name=row['product__name'])
    Source.objects.get_or_create(id=row['source__id'], name=row['source__name'], url = row['source__url'],
                                 currency_id=row['source__currency_id'])
    Parser.objects.get_or_create(script=row['script'], boolean=row['boolean'], product_id=row['product__id'],
                                 source_id=row['source__id'])
return 'Done'

但是,django会通过queryset显示我的模型对象 在python manage.py shell

from Parser.models import *
Product.objects.all()  
<QuerySet [<Product: test product>, <Product: iphone>, <Product: 
Mac>, <Product: iPad>]>  

然而,当我运行python manage.py dbshell > select * from Parser_product;时 我得到ERROR: relation "parser_product" does not exist

我在Debian上使用Docker,这是远程完成的。

2 个答案:

答案 0 :(得分:1)

很高兴我在电报中通过python聊天找到了解决方案。

答案是原始查询

我必须让它成为SELECT * FROM "Parser_product"&lt;请注意引号。

感谢answer

答案 1 :(得分:0)

尝试运行makemigration命令以及应用名称。如果您在默认应用程序中有模型,则需要这样做。例如 - python manage.py makemigrations parser。然后运行migrate命令。