简体   繁体   中英

Reverse Get item by foreign key django template

I'm trying to build CMS like menu models.

So in MODELS.PY :

class MenuItem(models.Model):
    class Meta():
        db_table = "menu_item"
        verbose_name = "Menu Item"
        verbose_name_plural = "Menu Items"

    menu_item_title = models.CharField(
        verbose_name="Menu Item Custom URL title",
        max_length=200,
        blank=False,
        null=False,
    )
    menu_item_type = models.ForeignKey(
        MenuType,
        related_name="menu_item_type_key",
        blank=False,
        null=False,
    )

class MenuItemCustomUrl(models.Model):
    class Meta():
        db_table = "menu_item_custom_url"
        verbose_name = "Menu Item Custom URL"
        verbose_name_plural = "Menu Items Custom URL"

    menu_item_custom_url = models.CharField(
        verbose_name="URL address that points menu item",
        max_length=200,
        blank=False,
        null=False,
    )
    menu_item_custom_url_menu_item = models.ForeignKey(
        MenuItem,
        unique=True,
        on_delete=models.CASCADE,
        related_name="menu_item_custom_url_menu_item_key",
        blank=False,
        null=False
    )

in VIEWS.PY :

def homepage(request):
    args['menu_items'] = MenuItem.objects.filter(menu_item_menu=args['main_menu'])
    return render(request, template_page, args)

and TEMPLATE :

{% for menu_item in menu_items %}
    <li>
        <a href="#">
            {{ menu_item }}
        </a>
    </li>
{% endfor %}

So, as you see the every menu_item has attached menu_item_custom_url , and what I need is to use menu_item_custom_url value in menu_item loop

NOTE : Beside custopm_url type there are also other types with their own parameter...

virtualenv, django=1.11, python=3.4, ubuntu=14.04

If you extend your model with a method to find the correct sub-object:

class MenuItem(models.Model):
    def custom_url(self):
        return self.menuitemcustomurl_set.first()  # assume the first one is correct
    ...

then you can use this method in you template directly

{{ menu_item.custom_url }}

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