简体   繁体   中英

django access child model foreign field in parent model

i have two model namely Parent and Child and i have created inline formset CRUD of Parent and Child model.My inline formset CRUD is working fine.But the problem is, i can't show the Child fields data in 'parent list view' in template.What i have done is that,i have use @property to grab Child models data but seems its not working.

There might be problem in my django template while showing data in higher level or might be the problem is in @property written in Parent model.

After a long investigation,can't figure out the problem.data is not showing.

My Parent model:

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']
    ]

and my Child model:

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

and this is Attribute model which is foreig key in Child .I want to show the date from 'Attribute' model.

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') 

and this the html template where i want to show the 'Attribute' models data which is foreign key in Child model.

    {% 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 %}

Update :

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)

in the template you have

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

the second .all might be causing the issue, child_set is a query set and .all should be sufficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM