你好,这是我在这里的第一篇文章。我是新来python和django我试图更多地了解这两个,所以我和他们一起工作,以获得更多的经验。我试图让所有metros的user(x)可以说1。我希望能有user 1作为id,并得到所有metros与此有关user。楷模from django.db import modelsfrom django.utils import timezonefrom django.contrib.auth.models import User# Create your models here.class Metro(models.Model):class Meta(): verbose_name_plural = "MetroCards" owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Creator") metro_name = models.CharField( max_length=30) created = models.DateTimeField(default=timezone.now) def __str__(self): return f"{self.metro_name} by: {self.owner}"观看次数from django.shortcuts import render, redirect, Http404from .models import User, Metrofrom django.contrib.auth import login, authenticatefrom django.contrib.auth.forms import UserCreationFormdef user(request, user_id): try: user = User.objects.get(pk=user_id) metro = Metro.owner.get(pk=user_id) except User.DoesNotExist: raise Http404("User Does Not Exist") context = { "user": user, "metro": metro } return render(request, "metrocard/user.html", context)网址from django.urls import pathfrom . import viewsurlpatterns = [ path('', views.index, name='index'), path('register/', views.register, name='register'), path("user/<str:user_id>", views.user, name="userid"), path('map/', views.map, name='map'),]html<h1>User Id: {{ user.id}} </h1><ul> <li>Username: {{ user.username }} </li> <li>Email: {{ user.email }} </li> {% for met in metro %} <li>Metro Name: {{ met.metro_name }}</li> {% endfor %}</ul>我得到的错误是:'ForwardManyToOneDescriptor' object has no attribute 'get'
2 回答
交互式爱情
TA贡献1712条经验 获得超3个赞
我认为在你看来你应该改变:
metro = Metro.owner.get(pk=user_id)
到
metro = user.metro_set.all()
繁星点点滴滴
TA贡献1803条经验 获得超3个赞
模型.py
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField(blank=True)
price = models.TextField()
视图.py
def dynamic_lookup_view(request,my_id):
object = Product.objects.get(id=my_id)
context = {
'product':object
}
return render(request,'products/product_detail.html',context)
网址.py
path('products/<int:my_id>/',dynamic_lookup_view)
HTML
{{ product.title }}
{{ product.description }}
添加回答
举报
0/150
提交
取消