简体   繁体   中英

Django Foreign key relation views.py and template html

I have 3 tables related for listing a product with features, i want to list FeatureItem values with for loop in template html file. I ve tried to write a view class but i couldn't succeed. Any Suggestion which approach for views.py and template.html file would be best solution? Thanks.

class Item(models.Model):
    title = models.CharField(max_length=100)
    price = models.FloatField()
    slug = models.SlugField()
    category = models.ForeignKey(Category,  on_delete=models.CASCADE)
    feature = models.ForeignKey(Feature, on_delete=models.CASCADE)

class FeatureItem(models.Model):
    feature_title = models.CharField(max_length=100)
    feature_description = models.CharField(max_length=100)
    feature_id = models.ForeignKey(Feature, on_delete=models.CASCADE)

class Feature(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()

urls.py:

urlpatterns = [
    ...
    path('some_url', views.some_view_function, name='some_url'),
    ...
]

views.py:

def some_view_function(request):
 
    feature_items = models.FeatureItem.objects.all()
 
    context = {
        'feature_items' : feature_items,
         ... 
    }

    return render(request, 'some_template.html', context=context)

some_template.html:

...
<div>
{% for feature_item in feature_items %}
  Title: {{ feature_item.feature_title }}
{% endfor %}
...

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