Okay, I have been reading other django inheritance questions and I can't find anything to help. I may just have an understanding issue about how inheritance works. But here is my issue. To start, I have two base models that I'd like all of my other models to inherit from. Base Model just contains some useful methods for all of my models. The second is the start of an account specific object.
class BaseModel(models.Model):
# A couple of methods that all my models need to have. No fields.
class AccountModel(models.Model):
''' A base model for items related to a specific account'''
account = models.ForeignKey(Account)
def save(self, request, *args, **kwargs):
self.account = request.session['account']
super(AccountModel, self).save(*args, **kwargs)
Then I have three models:
class Keyword(AccountModel) :
keyword = models.CharField(max_length=300)
#other fields, none required...
开发者_StackOverflow社区
class Project(AccountModel) :
project_name = models.CharField(max_length=200,verbose_name="Project Name")
#other fields..
class KeywordTarget(BaseModel):
keyword = models.ForeignKey(Keyword)
url = models.URLField(null=True,blank=True)
project = models.ForeignKey(Project)
But when I try to create a new Keyword, I get this error:
ValueError: Cannot assign "'something'": "Keyword.keyword" must be a "Keyword" instance.
when I do:
kw = Keyword(keyword = "something")
Where am I going wrong?
(Also, please don't tell me I should be using a ManyToMany through unless it solves the problem at hand)
It looks like both BaseModel and Account model will be abstract, so you should specify that in the models' Meta objects like:
class BaseModel(models.Model):
...
class Meta:
abstract=True
(see http://docs.djangoproject.com/en/dev/topics/db/models/#abstract-base-classes)
I'm guessing that without that, you're ending up with interference between the inheriting models.
精彩评论