Django 2.1.7 - 从用户(x)检索所有模型字段

你好,这是我在这里的第一篇文章。我是新来python和django我试图更多地了解这两个,所以我和他们一起工作,以获得更多的经验。


我试图让所有metros的user(x)可以说1。我希望能有user 1作为id,并得到所有metros与此有关user。


楷模


from django.db import models

from django.utils import timezone

from 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, Http404

from .models import User, Metro

from django.contrib.auth import login, authenticate

from django.contrib.auth.forms import UserCreationForm

def 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 path

from . import views


urlpatterns = [

    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'



慕尼黑8549860
浏览 204回答 2
2回答

交互式爱情

我认为在你看来你应该改变:&nbsp;&nbsp;&nbsp;&nbsp;metro&nbsp;=&nbsp;Metro.owner.get(pk=user_id)到&nbsp;&nbsp;&nbsp;&nbsp;metro&nbsp;=&nbsp;user.metro_set.all()

繁星点点滴滴

模型.pyclass Product(models.Model):&nbsp;&nbsp; &nbsp; title = models.CharField(max_length=120)&nbsp; &nbsp; description = models.TextField(blank=True)&nbsp; &nbsp; price = models.TextField()视图.pydef dynamic_lookup_view(request,my_id):&nbsp; &nbsp; object = Product.objects.get(id=my_id)&nbsp; &nbsp; context = {&nbsp; &nbsp; &nbsp; &nbsp; 'product':object&nbsp; &nbsp; }&nbsp; &nbsp; return render(request,'products/product_detail.html',context)网址.pypath('products/<int:my_id>/',dynamic_lookup_view)HTML{{ product.title }}{{ product.description }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python