简体   繁体   English

Django,访问 model 方法

[英]Django, accessing model methods

In the Django documentation, they recommend writing business logic in Model.在 Django 文档中,他们建议在 Model 中编写业务逻辑。

How do the View layer or queryset access the methods in Model?视图层或查询集如何访问 Model 中的方法?

As per example in documentation ( https://docs.djangoproject.com/en/3.0/topics/db/models/ )根据文档中的示例( https://docs.djangoproject.com/en/3.0/topics/db/models/

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()

    def baby_boomer_status(self):
        "Returns the person's baby-boomer status."
        import datetime
        if self.birth_date < datetime.date(1945, 8, 1):
            return "Pre-boomer"
        elif self.birth_date < datetime.date(1965, 1, 1):
            return "Baby boomer"
        else:
            return "Post-boomer"

How do view layer access the baby_boomer_status ?视图层如何访问baby_boomer_status

I have a little experienced in Django development but I used to write logics in View itself.我在 Django 开发方面有一点经验,但我曾经在 View 本身中编写逻辑。

You can just call the method on the person instance:您可以在 person 实例上调用该方法:

person = Person.objects.get(id=1)
print(person.baby_boomer_status())

You can iterate over QuerySet and call the model method as您可以遍历 QuerySet 并调用 model 方法

for person in Person.objects.all():
    print(person.baby_boomer_status())

If you have a single object, just call the method directly as,如果你有单个object,直接调用方法为,

print(Person.objects.get(pk=123).baby_boomer_status())

This can be done by simply calling function.这可以通过简单地调用 function 来完成。 For example,例如,

>>> from .models import Person
>>> person = Person.objects.get(id=1) # Remember getting the person object
>>> person.baby_boomer_status()

You have to first get person object otherwise, it will return function itself, eg你必须先得到人 object 否则,它将返回 function 本身,例如

>>> from .models import Person
>>> person.baby_boomer_status()
>>> <function AppName.models.Person.baby_boomer_status(self)>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM