我的Django数据库.save()正在抛出异常。有没有办法找出原因?
我的主要代码是:
for i in data['movies']:
try:
id = i['regions'][0]['products'][0]['product_id']
title = i['regions'][0]['products'][0]['product_title']
m = Movie.objects.get(preview_id=id)
except Movie.DoesNotExist:
try:
movie = Movie()
movie.preview_id = id
movie.title = title
movie.details = i['regions'][0]['products'][0]['description']
movie.date = i['regions'][0]['products'][0]['upd_date']
movie.trailer = i['regions'][0]['products'][0]['clips'][0]['files'][0]['url']
movie.likes = 0
movie.dislikes = 0
movie.save() # THIS IS THROWING AN ERROR
print id + ": " + title
for genre in i['regions'][0]['categories']:
try:
g = Genre.objects.get(title__exact=genre['name'])
movie.genres.add(g)
except Genre.DoesNotExist:
g = Genre(title=genre['name'])
g.save()
movie.genres.add(g)
for pic in i['regions'][0]['pictures']:
if pic['type_name'] == "poster_large":
movie.picture = pic['url']
movie.save()
except:
print 'error'
print 'Success'
我的电影模型如下:
class Movie(models.Model):
# Movie Model store all the detail of a movie
# Each movie is created by a User
user = models.ForeignKey(User)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, blank=True, null=True)
details = models.TextField()
picture = models.ImageField(upload_to=filename, blank=True, null=True)
trailer = models.FileField(upload_to=videoname, blank=True, null=True)
# genres = ManyToMany with Genre Model
genres = models.ManyToManyField(Genre, related_name='genres')
likes = models.BigIntegerField(blank=True, null=True)
dislikes = models.BigIntegerField(blank=True, null=True)
trigahs = models.BigIntegerField(blank=True, null=True)
# Director with People Model
director = models.ForeignKey(People, blank=True, null=True)
# Casts = ManyToMany with People Model
casts = models.ManyToManyField(People, related_name='casts', blank=True, null=True)
date = models.DateField(blank=True, null=True)
amazon_id = models.CharField(max_length=200, blank=True, null=True)
preview_id = models.BigIntegerField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True)
def add_likes(self):
self.likes = self.likes + 1
self.save()
def add_dislikes(self):
self.dislikes = self.dislikes + 1
self.save()
def save(self):
super(Movie, self).save()
if not self.slug:
self.slug = '%s' % (
slugify(self.title)
)
super(Movie, self).save()
超级函数定义如下:
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
"""
Saves the current instance. Override this in a subclass if you want to
control the saving process.
The 'force_insert' and 'force_update' parameters can be used to insist
that the "save" must be an SQL insert or update (or equivalent for
non-SQL backends), respectively. Normally, they should not be set.
"""
# Ensure that a model instance without a PK hasn't been assigned to
# a ForeignKey or OneToOneField on this model. If the field is
# nullable, allowing the save() would result in silent data loss.
for field in self._meta.concrete_fields:
if field.is_relation:
# If the related field isn't cached, then an instance hasn't
# been assigned and there's no need to worry about this check.
try:
getattr(self, field.get_cache_name())
except AttributeError:
continue
obj = getattr(self, field.name, None)
# A pk may have been assigned manually to a model instance not
# saved to the database (or auto-generated in a case like
# UUIDField), but we allow the save to proceed and rely on the
# database to raise an IntegrityError if applicable. If
# constraints aren't supported by the database, there's the
# unavoidable risk of data corruption.
if obj and obj.pk is None:
raise ValueError(
"save() prohibited to prevent data loss due to "
"unsaved related object '%s'." % field.name
)
using = using or router.db_for_write(self.__class__, instance=self)
if force_insert and (force_update or update_fields):
raise ValueError("Cannot force both insert and updating in model saving.")
if update_fields is not None:
# If update_fields is empty, skip the save. We do also check for
# no-op saves later on for inheritance cases. This bailout is
# still needed for skipping signal sending.
if len(update_fields) == 0:
return
update_fields = frozenset(update_fields)
field_names = set()
for field in self._meta.fields:
if not field.primary_key:
field_names.add(field.name)
if field.name != field.attname:
field_names.add(field.attname)
non_model_fields = update_fields.difference(field_names)
if non_model_fields:
raise ValueError("The following fields do not exist in this "
"model or are m2m fields: %s"
% ', '.join(non_model_fields))
# If saving to the same database, and this model is deferred, then
# automatically do a "update_fields" save on the loaded fields.
elif not force_insert and self._deferred and using == self._state.db:
field_names = set()
for field in self._meta.concrete_fields:
if not field.primary_key and not hasattr(field, 'through'):
field_names.add(field.attname)
deferred_fields = [
f.attname for f in self._meta.fields
if (f.attname not in self.__dict__ and
isinstance(self.__class__.__dict__[f.attname], DeferredAttribute))
]
loaded_fields = field_names.difference(deferred_fields)
if loaded_fields:
update_fields = frozenset(loaded_fields)
self.save_base(using=using, force_insert=force_insert,
force_update=force_update, update_fields=update_fields)
save.alters_data = True
这就是我所接受的所有代码,这对我来说是个谜。如果这个问题没有得到妥善处理,请道歉。但是如果能找到失败的原因,可以用指针来做真的。
答案 0 :(得分:3)
try:
line 1
line 2
except Exception as e:
print e
这将揭示错误。这仅用于调试。你应该妥善处理例外情况。