Query.get引发对象匹配查询不存在错误

时间:2011-10-20 13:54:51

标签: django django-models

我需要有关此代码的帮助:

>>> t = Transaction.objects.filter(paid=True)
>>> t
[<Transaction: ac0e95f6cd994cc39807d986f7a10d4d>, <Transaction: 7067361871fd459f
aa144988ffa22c7c>, <Transaction: 134e5ab4b0a74b5a985ff53e31370818>, <Transaction
: ef451670efad4995bff755621c162807>]
>>> t[0]
<Transaction: ac0e95f6cd994cc39807d986f7a10d4d>
>>> t[0].branch_name
<Branch: WAREHOUSE ROAD>
>>> Transaction.objects.get(branch_name='WAREHOUSE ROAD')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\mana
ger.py", line 132, in get
    return self.get_query_set().get(*args, **kwargs)
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 344, in get
    num = len(clone)
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 82, in __len__
    self._result_cache = list(self.iterator())
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 273, in iterator
    for row in compiler.results_iter():
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\sql\
compiler.py", line 680, in results_iter
    for rows in self.execute_sql(MULTI):
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\sql\
compiler.py", line 735, in execute_sql
    cursor.execute(sql, params)
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\backends\ut
il.py", line 34, in execute
    return self.cursor.execute(sql, params)
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\backends\my
sql\base.py", line 86, in execute
    return self.cursor.execute(query, args)
  File "build\bdist.win32\egg\MySQLdb\cursors.py", line 176, in execute
    if not self._defer_warnings: self._warning_check()
  File "build\bdist.win32\egg\MySQLdb\cursors.py", line 92, in _warning_check
    warn(w[-1], self.Warning, 3)
Warning: Truncated incorrect DOUBLE value: 'WAREHOUSE ROAD'

这是分支和交易模型:

class Branch(models.Model):
    """ Branch """
    bid = models.AutoField(primary_key=True)
    institution = models.CharField(max_length=50)
    branchcode = models.CharField(max_length=50)
    name_branch = models.CharField(max_length=255)
    name_branch_short = models.CharField(max_length=50)
    address_1 = models.CharField(max_length=100)
    name_city = models.CharField(max_length=50)
    name_state = models.CharField(max_length=50)
    sector = models.CharField(max_length=50)

    class Meta:
        db_table = u'branch'

    def __unicode__(self):
        return self.name_branch

class Transaction(models.Model):
    """Gateway transactions"""
    id = models.AutoField(primary_key=True)
    tpin = UUIDField(max_length=32, blank=True, editable=False,\
        help_text='Transaction Payment Identification Number')
    user_id = models.IntegerField(help_text='The user who made the transaction')
    amount = models.DecimalField(max_digits=14, decimal_places=2, \
        help_text='Transaction amount')
    identifier = models.CharField(max_length=100, blank=True, \
        help_text='A unique identifier provided by the student')
    institution = models.ForeignKey(Institution, related_name='transactions')
    financial_institution = models.ForeignKey('FinancialInstitution', blank=True, null=True, related_name='transactions', help_text='The financial institution this transaction was updated in')
    branch_name = models.ForeignKey(Branch, blank=True, null=True, related_name='transactions', \
        help_text='The bank branch where this transaction is originating from')
    paid = models.BooleanField(default=False)
    teller_no = models.CharField(max_length=20, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    audit_log = AuditLog(exclude=['created', 'updated', ])

    def __unicode__(self):
        return self.tpin

    def natural_key(self):
        """ A natural key is a tuple of values that can be used to uniquely identify an object 
        instance without using the primary key value.
        """
        return self.tpin

我试图像这样序列化事务:

>>> from django.core import serializers
>>> serializers.serialize('csv', t)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\__init__.py", line 91, in serialize
    s.serialize(queryset, **options)
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\base.py", line 48, in serialize
    self.handle_fk_field(obj, field)
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\python.py", line 48, in handle_fk_field
    related = getattr(obj, field.name)
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\fiel
ds\related.py", line 315, in __get__
    rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 349, in get
    % self.model._meta.object_name)
DoesNotExist: Branch matching query does not exist.

我不明白为什么get会在Branch上返回DoesNotExists。我在上面展示了一个示例,其中显示Branch在Transaction中有记录。

循环播放,我得到一个结果,但接着是DoesNotExist:分支匹配查询不存在

>>> for i in t:
...     i.branch_name
...
<Branch: WAREHOUSE ROAD>
Traceback (most recent call last):
  File "<console>", line 2, in <module>
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\fiel
ds\related.py", line 315, in __get__
    rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
  File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 349, in get
    % self.model._meta.object_name)
DoesNotExist: Branch matching query does not exist.

请帮忙。感谢

1 个答案:

答案 0 :(得分:2)

此查询:

Transaction.objects.get(branch_name='WAREHOUSE ROAD')

过滤branch_name ForeignKey字段。要查询该名称,您应该使用两个下划线:

Transaction.objects.get(branch_name__name_branch='WAREHOUSE ROAD')

不是您字段最方便的名称......