In a Django 1.6 project, I am using a model structure with a foreign key dependency as shown below. In my ParentModel method mixin, I need to add a method that creates new ChildModel instances with the parent foreign key as the "self" in the method context.

I have successfully implemented this by importing the ChildModel from within the ParentModel method, but I am wondering if there is a cleaner way of achieving this. When I try to directly import Child model at the top level in mixins.py, I get an import error that is due to the cross-imports I suppose.

Is there a way avoiding the import form within the ParentModel method here?

And if not, out of curiosity, what is the overhead of having the ChildImport on-the-fly from within the method? Or does python import the method every time or is that code cached somehow?

models.py

from .mixins import ParentMixins

class ParentModel(models.Model, ParentMixins):
    name = models.TextField()

class ChildModel(models.Model):
    parent = models.ForeignKey(ParentModel)

mixins.py

class ParentMixins(object):
     def create_child(self):
         from .models import ChildModel
         ChildModel.create(parent=self)
有帮助吗?

解决方案

Assuming you can guarantee any class doesn't define a related_name for the parent field, you can just do this in your create_child method:

self.childmodel_set.create()

Then there's no need to do the import at all.

(Although I must admit I'm a bit confused about the idea of having a mixin dependent on fields in the concrete model that it's not actually providing itself.)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top