考虑下一个例子:
class Vehicle(models.Model):
vehicle = models.CharField(_('veículo'), max_length=50, unique=True)
price = models.DecimalField(_(u'preço'), max_digits=8, decimal_places=2)
kit_fabric = models.ForeignKey(
"Kit", verbose_name=u'kit de fábrica', related_name='vehicle_kit')
class Accessory(models.Model):
accessory = models.CharField(_(u'accessório'), max_length=50)
price_accessory = models.DecimalField(
_(u'preço'), max_digits=8, decimal_places=2)
class Kit(models.Model):
kit = models.CharField(max_length=50)
class KitDetail(models.Model):
kit = models.ForeignKey("Kit", verbose_name='kit', related_name='kit_det')
accessory = models.ForeignKey(
"Accessory", verbose_name=u'accessório', related_name='accessory_kit')
quantity_accessory = models.PositiveIntegerField(_('quantidade'))
def __str__(self):
return str(self.kit)
class Ordered(TimeStampedModel):
customer = models.ForeignKey("Customer", verbose_name='cliente')
employee = models.ForeignKey("Employee", verbose_name=u'funcionário')
vehicle = models.ForeignKey("Vehicle", verbose_name=u'veículo')
kit_optional = models.ForeignKey("Kit", verbose_name='kit opcional')
dealership = models.ForeignKey(
"Dealership", verbose_name=u'concessionária')
kiosk = models.ForeignKey("Kiosk", verbose_name='quiosque')
status = models.CharField(max_length=2, choices=status_list, default='p')
如何通过订购中的附件返回描述?
也就是说,在我需要的模板中:
{{ object.kit_optional.accessory }}
{{ object.kit_optional.price_accessory }}
{{ object.kit_optional.quantity_accessory }}
否则,我会尝试其他代码,但不能正常工作。
我试试
$ ./manage.py shell
>>> from new_way.core.models import Ordered, Customer, KitDetail
>>> ordered.kit_optional.kit_det.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
NameError: name 'ordered' is not defined
>>> Ordered.kit_optional.kit_det.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'ReverseSingleRelatedObjectDescriptor' object has no attribute 'kit_det'
但不行。
我不知道怎么做。
答案 0 :(得分:0)
ForeignKey
的每个定义都会添加一个反向关系,可以使用related_name
进行访问(默认情况下,它是$model_name_lowercase$_set
)。因此,您可以使用以下代码来访问所需的对象:
ordered.kit_optional.kit_det.all() # Returns all KitDetail objects, related to oredered.kit_optional
您可以迭代它并为每个Accessory
检索相关的KitDetail
个对象集:
{% for kit_detail in ordered.kit_optional.kit_det.all %}
{{ kit_detail.quantity_accessory }}
{% for accessory in kit_detail.accessory_kit.all %}
{{ accessory.accessory }}
{{ accessory.price_accessory }}
{% endfor %}
{% endfor %}