Django模型manager.py和models.py [英] Django model managers.py and models.py

查看:87
本文介绍了Django模型manager.py和models.py的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出现以下情况:
models.py

from .managers import PersonManager
from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=256)
    last_name = models.CharField(max_length=256)

managers.py

from .models import Person
from django.db import managers

class PersonManager(models.Manager):
    def create(self, person_dict):
        new_person = Person(
            first_name=person_dict['first_name']
            last_name=person_dict['last_name'])
        new_person.save()

如何编写模型管理器以避免循环导入?
实际上是行不通的,我的猜测是我必须在我的管理器中创建对象,而不必将其称为Person类,而应该使用更通用的通用Django名称。有什么想法吗?

How can I write my model manager to avoid circular import? It is actually not working, my guess is that I would have to create my object inside my manager without refering to it as class Person, instead I should use a more general generic Django name. Any thoughts?

推荐答案

这里有一些选择。

首先,您可以在同一文件中定义模型和管理器; Python没有要求或期望每个类都在其自己的文件中。

Firstly, you could define the model and the manager in the same file; Python has no requirement or expectation that each class is in its own file.

第二,您实际上不需要将模型导入到管理器中。管理者属于模型,而不是模型。在管理器中,您可以通过 self.model 引用模型类。

Secondly, you don't actually need to import the model into the manager. Managers belong to models, not the other way round; from within the manager, you can refer to the model class via self.model.

最后,如果那是您的经理所做的一切,完全没有理由。管理者已经有了 create 方法;它使用关键字参数而不是字典,但这仅意味着您可以使用 Person.objects.create(** person_dict)来调用它。

And finally, if that's all your manager is doing, there is no reason for it at all. Managers already have a create method; it takes keyword parameters, rather than a dict, but that just means you can call it with Person.objects.create(**person_dict).

这篇关于Django模型manager.py和models.py的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆