我想根據外鍵的特定字段的值過濾Django中的表。Django過濾外鍵屬性
我的車型有:
class Retailer(SCOPEModel):
""" A business or person that exchanges goods for vouchers with recipients
"""
office = models.ForeignKey(Office, related_name='retailers')
uuid = UUIDField(auto=True, version=4, null=True, help_text=_('unique id'))
name = models.CharField(_('Name'), max_length=50, validators=[validate_sluggable],
help_text=_('Name of the retail shop'), blank=False)
location = models.ForeignKey(Location, verbose_name=_('location'), blank=True, null=True,
help_text=_('Location of the retail shop'), related_name='retailers')
class PointOfSaleTerminalAssignment(SCOPEModel):
"""Point Of Sale (POS) is the location where a transaction occurs for
exchange of goods and services
and a POS terminal is the hardware used to perform the transactions.
These terminals are registered in the system.
POS' are managed at office level
"""
office = models.ForeignKey(Office, related_name='pos_terminals')
terminal_type = models.ForeignKey(
TerminalType,
verbose_name=_('Terminal'),
help_text=_("Device | Make (model)"),
)
wfp_number = models.CharField(
_('WFP Number'),
max_length=50,
unique=True,
validators=[validate_sluggable],
help_text=_("WFP unique generated number e.g. Inventory number")
)
serial_number = models.CharField(
_('Serial Number'),
max_length=50,
unique=True,
help_text=_('Hardware device serial number')
)
slug = models.SlugField(
editable=False,
unique=True,
help_text=_('Unique ID generated from the WFP number')
)
assigned_retailer = models.ForeignKey(
Retailer,
related_name='pos_terminals',
null=True,
blank=True,
help_text=_('Retailer this POS terminal is assigned to')
)
我希望得到零售商的詳細信息和分配給他們的POS機的序列號 目前我執行兩個查詢:
from maidea.apps.office.models import Office
from maidea.apps.redemption.models import Retailer, PointOfSaleTerminalAssignment
office = Office.objects.get(slug='so-co')
pos = PointOfSaleTerminalAssignment.objects.filter(office=office)
for p in pos:
retailer = p.assigned_retailer
print retailer.name
首先,你的代碼不能產生這樣的錯誤,因爲你要打印'retailer.name',並在錯誤'NoneType'對象有沒有屬性''location'' –