Django-视图调用模型的方法时出现名称错误

时间:2018-09-16 06:04:33

标签: django methods nameerror

我是Django的新手。我已经定义了模型和方法

from django.db import models
from django.contrib.auth.models import User

class Practice(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=200)
    phone = models.IntegerField()

    def __str__(self):
        return self.name

class Doctor(models.Model):
    specialisation = models.CharField(max_length=50)
    practice = models.ForeignKey(Practice, related_name='doctor',on_delete=models.DO_NOTHING)
    name = models.ForeignKey(User, related_name ='doctor', on_delete=models.DO_NOTHING)
    selected = models.BooleanField()


    def __str__(self):
        return self.specialisation

    def get_list_doctors(self):
        all_doctors = User.objects.exclude(pk=1).filter(doctor__isnull=False)
        all_doctors_names = all_doctors.values_list('last_name', 'first_name')
        return all_doctors_names

class Patient(models.Model):
    name = models.ForeignKey(User, related_name='patient', on_delete=models.DO_NOTHING)
    height = models.DecimalField(max_digits=6, decimal_places=2)
    weight = models.DecimalField(max_digits=6, decimal_places=2)
    practice = models.ForeignKey(Practice, related_name='patient',on_delete=models.DO_NOTHING)
    primary_doctor = models.ForeignKey(Doctor, related_name='patient',on_delete=models.DO_NOTHING)


class Appointment(models.Model):
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    doctor = models.ForeignKey(Doctor, related_name='appointment',on_delete=models.DO_NOTHING)
    practice = models.ForeignKey(Practice, related_name='appointment',on_delete=models.DO_NOTHING)
    patient = models.ForeignKey(Patient, related_name='appointment',on_delete=models.DO_NOTHING)

这是我的观点

def login_user(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            messages.success(request, ('You Have Been Logged In!'))

            doctor_list = get_list_doctors()
            context = { 'doctor_name': doctor_list}
            return render(request, 'homeunimed.html', context)

我正在尝试在视图中使用该方法。在模型中定义它的原因是为了可以重用。

NameError at /
name 'get_list_doctors' is not defined
Request Method: POST
Request URL:    http://localhost:8000/
Django Version: 2.1
Exception Type: NameError
Exception Value:    
name 'get_list_doctors' is not defined
Exception Location: /Users/vinoojacob/Django/my_app/authenticate/views.py in login_user, line 27
Python Executable:  /Users/vinoojacob/Django/bin/python
Python Version: 3.6.5
Python Path:    
['/Users/vinoojacob/Django/my_app',
 '/Users/vinoojacob/Django/lib/python36.zip',
 '/Users/vinoojacob/Django/lib/python3.6',
 '/Users/vinoojacob/Django/lib/python3.6/lib-dynload',
 '/Users/Shared/anaconda3/lib/python3.6',
 '/Users/vinoojacob/Django/lib/python3.6/site-packages']

但是,出现此错误。任何指示错误的指针。我以为只要导入模型,您就可以访问模型中定义的任何方法。感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

编写时可以通过模型访问它。因此,用@staticmethod装饰您的方法,省去self作为参数,并以这种方式doctor_list = Doctor.get_list_doctors()进行调用。

@staticmethod
def get_list_doctors():
    all_doctors = User.objects.exclude(pk=1).filter(doctor__isnull=False)
    all_doctors_names = all_doctors.values_list('last_name', 'first_name')
    return all_doctors_names

答案 1 :(得分:0)

函数get_list_doctors(self)几乎没有用,并且排除了用户对其pk进行硬编码的情况。这很糟糕。

一些建议:

1)更改Doctor中的行

 name = models.ForeignKey(User, related_name ='doctor', on_delete=models.DO_NOTHING)

使用:

user = models. OneToOneField(User, related_name ='doctor', on_delete=models.CASCADE)

该关系是一个用户,如果该用户不见了,那么您也必须删除Doctor。而且,这种关系是一对一的!

2)您可以很容易地获得医生名单

def login_user(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            messages.success(request, ('You Have Been Logged In!'))
            doctors_list = Doctor.objects.exclude(user=user)
            context = { 'doctors_list': doctors_list}
            return render(request, 'homeunimed.html', context)

在您的模板中,您可以通过用户访问医生的姓名(这是一个非常幼稚的示例)

{% for doctor in doctors_list %}
     First name: {{ doctor.user.first_name }}
     Last name: {{ doctor.user.last_name }}
{% endfor %}