【问题标题】:Django - Name Error when views call model's methodDjango - 视图调用模型方法时出现名称错误
【发布时间】:2018-09-16 06:04:33
【问题描述】:

我是 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']

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

【问题讨论】:

  • get_list_doctors 属于模型类。所以你只能在 Doctor 的模型实例上调用它。
  • 非常感谢。现在调用Doctor的模型实例解决了它。
  • 只有一条评论:由于您不在方法中使用实例,请考虑通过将 deocrator @classmethod 放在方法之前并删除 self 参数来将此方法设为静态方法。这不会改变功能,但会是正确的解决方案。

标签: django methods nameerror


【解决方案1】:

正如您所写,您可以通过模型访问它。所以用@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

【讨论】:

  • 谢谢!我认为需要一个实例,似乎不能直接在模型上工作。
  • @VinooPJacob 请查看编辑后的答案。我建议不要在对象实例上调用你的方法,因为你必须先有一个实例。您的方法返回所有医生,因此在 Doctor 模型上调用它更通用。这样您就可以在任何视图中调用它,即使在不包含医生实例的视图中也是如此。
  • 谢谢!!我不需要实例,因此将其设为静态很有意义。
  • @VinooPJacob 接受正确的答案会很棒。
【解决方案2】:

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 %}

【讨论】:

  • 谢谢。我将在删除时添加 CASCADE,使其保持整洁并且没有孤儿!根据您的第二个建议,我正在过滤(pk=1),只是为了从列表中删除“管理员”用户,而不是登录用户。我现在可以看到这不是一种优雅的方法,宁愿在数据中正确设置标志,以便过滤掉管理员而不是在代码中进行。不过很好。
  • 您可以轻松获取所有非管理员用户:User.objects.all().exclude(is_superuser=True)
  • 如果您满意,请为答案投票
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-31
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
相关资源
最近更新 更多