Issue
given the following situation: 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()
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?
Solution
There are a few options here.
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.
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
.
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)
.
Answered By - Daniel Roseman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.