django访问父模型中的子模型外部字段

时间:2016-02-29 06:56:38

标签: python django

我有两个模型,即ParentChild,我创建了ParentChild模型的内联formset CRUD。我的内联formset CRUD工作正常。但是问题是,我无法在父列表视图中显示Child字段数据'在模板中。我做的是,我使用@property来获取Child模型数据,但似乎无效。

我的django template在显示更高级别的数据时可能会出现问题,或者问题出现在@property模型中的Parent中。

经过长时间的调查,无法找出问题。数据没有显示。

我的Parent型号:

class Parent(AbstractBaseModel):

"""
Defining the facets header that will be used during search.
"""

validators = [ChainIntegrityValidator, ScreenMethodValidator]


chain = models.ForeignKey(
        'customers.Chain',
        verbose_name=_('chain')
    )
product_group = models.ForeignKey(
    'products.ProductGroup',
    help_text=_('The product group in which the parent belongs'),
    verbose_name=_('product group')
    )
price = models.BooleanField(
    default=False,
    help_text=_("Identifies whether the 'price' will be included in search facets.\
        Default value false"),
    verbose_name=_('price')
    )
order_price = models.DecimalField(
    max_digits=10,
    null=True,blank=True,
    decimal_places=2,
    help_text=_('Price of a order'),
    verbose_name=_('order price')
    )
monthly_fee = models.BooleanField(
    default=False,
    help_text=_("Identifies whether the 'monthly_fee' will be included in search facets.\
        Default value false"),
    verbose_name=_('monthly fee')
    )
order_monthly_fee = models.IntegerField(
    null=True,blank=True,
    help_text=_('Sorting order of monthly fee.'),
    verbose_name=_('order monthly fee')
    )




def screen_product_group(self):
    if hasattr(self, 'product_group'):
        try:
            obj = Parent.objects.get(chain=self.chain, product_group__name=self.product_group)
        except Parent.DoesNotExist:
            obj = self

        if obj != self:
            return {'product_group': ['A facet header with this product_group already exists']}

@property
def child_attributes_name(self):

    return ','.join([child.attribute.name for child in
                     self.child_set.all()])

class Meta:
    app_label = 'search'
    unique_together = ('chain', 'product_group')
    index_together = [
        ['chain', 'product_group']
    ]

和我的Child模型:

class Child(AbstractBaseModel):

"""
Defining the facets lines that will be used during search.
"""

validators = [ChainIntegrityValidator, ScreenMethodValidator]

chain = models.ForeignKey(
    'customers.Chain',
    verbose_name=_('chain')
    )
parent = models.ForeignKey(
    'search.Parent',
    help_text=_('parent to which child belongs'),
    verbose_name=_('parent')
    )
attribute = models.ForeignKey(
    'products.Attribute',
    help_text=_("attribute to which child belongs"),
    verbose_name=_("attribute"),
    )
order_attribute = models.IntegerField(
    null=True,blank=True,
    help_text=_('Sorting order of attribute'),
    verbose_name=_('order attribute')
    )

class Meta:
    app_label = 'search'
    unique_together = ('chain','facet_header','attribute')
    index_together = [
        ['chain','facet_header','attribute']
    ]

def screen_chain(self):
    if not hasattr(self, 'chain'):
        self.chain = self.facet_header.chain

这是Attribute模型,它是Child中的foreig键。我想显示来自'属性'的日期。模型。

class Attribute(AbstractBaseModel):


validators = [ScreenMethodValidator, ChainIntegrityValidator]


attribute_group = models.ForeignKey(AttributeGroup, related_name='attributes')
name = models.CharField(max_length=128,
                        verbose_name=_('name'),
                        help_text=_('Enter Name'))
code = models.SlugField(
    verbose_name=_('Code'),
    help_text=_('Enter Code'),
    max_length=128, )

class Meta:
    app_label = 'products'
    ordering = ['attribute_group', 'code']
    unique_together = ('attribute_group', 'code')
    verbose_name = _('Attribute')
    verbose_name_plural = _('Attributes') 

这是html模板,我想在其中显示'属性'模拟Child模型中的外键数据。

    {% for data in object_list %}
                    <tr class="gradeX">
                        <td class="hidden-xs">{{ data.product_group }} </td>

                        <td class="hidden-xs">{{ data.price }}</td>
                        <td class="hidden-xs">{{ data.order_price }}</td>
                        <td class="hidden-xs">{{ data.monthly_fee }}</td>
                        <td class="hidden-xs">{{ data.order_monthly_fee }}</td>


                        <td class="hidden-xs">
                            <dl class="dl-horizontal">
                                {% for child in data.child_set.all.all %}
                                    <dt>{{ child.attribute.attribute_group.name }}</dt>
                                    <dd>{{ child.attribute.name }}</dd>
                                {% endfor %}
                            </dl>
                        </td>

                {% endfor %}

更新

class FacetsList(WammuListView):
    template_name = 'dashboard/parent_list.html'
    model = Parent

def get_queryset(self):
    chain = Chain.objects.filter(id=self.kwargs['chain_pk'])
    return Parent.objects.filter(chain=chain)

1 个答案:

答案 0 :(得分:0)

在您拥有的模板中

{% for child in data.child_set.all.all %}

第二个.all可能导致问题,child_set是一个查询集,而.all应该足够了。