所以我试图使用postgres(postgis)数据库在django中填充模型。我遇到的问题是输入datetimefield。我编写了一个填充脚本,但每次运行它都会出现错误django.db.utils.IntegrityError: null value in column "pub_date" violates not-null constraint
。下面的代码显示了我的模型以及适用于该表的填充脚本部分。
模特:
class Article(models.Model):
authors = models.ManyToManyField(Author)
location = models.ForeignKey(Location)
article_title = models.CharField(max_length=200, unique_for_date="pub_date")
pub_date = models.DateTimeField('date published')
article_keywords = ArrayField(ArrayField(models.CharField(max_length=20, blank=True), size=8), size=8,)
title_id = models.CharField(max_length=200)
section_id = models.CharField(max_length=200)
人口脚本:
def populate():
add_article(
id = "1",
article_title = "Obama scrambles to get sceptics in Congress to support Iran nuclear deal",
pub_date = "2015-04-06T20:38:59Z",
article_keywords = "{obama, iran, debate, congress, america, un, republican, democrat, nuclear, isreal}",
title_id = "white-house-scrambles-sceptics-congress-iran-nuclear-deal",
section_id = "us-news",
location_id = "1"
)
def add_article(id, article_title, pub_date, article_keywords, title_id, section_id, location_id):
article = Article.objects.get_or_create(article_title=article_title)[0]
article.id
article.article_title
article.pub_date
article.article_keywords
article.title_id
article.section_id
article.location_id
article.save()
return article
if __name__ == '__main__':
print "Starting Newsmap population script..."
populate()
我已经搜索了很多年,但似乎没有解决这个具体问题的方法。任何帮助非常感谢!!
答案 0 :(得分:1)
问题是,如果不存在新对象,则不会将Article.objects.get_or_create
传递给创建新对象所需的数据。
您需要做的是(参见documentation for get_or_create):
article = Article.objects.get_or_create(
article_title=article_title,
pub_date=pub_date,
defaults={
'id': id,
'article_keywords': article_keywords,
# etc...
}
)[0]
使用defaults
参数传递的数据仅用于创建新对象。使用其他关键字参数传递的数据将用于检查现有对象是否在数据库中匹配。