在 Django 中使用"Self"关键字和一对多关系调用属性



我是Django的新手,与JS或C#中的this相比,我很难理解self关键字是如何工作的。我一直在学习Django REST API教程,现在正在尝试添加第二个Model类。我希望每个SnippetSubSnippets之间有一对多的关系,但希望我的SubSnippets继承父Snippet的语言和样式属性,以便我可以在formatter中为每个SubSnippet使用它们。这是我添加到models.py:的代码

class SubSnip(models.Model):
snippet = models.ForeignKey(Snippet, on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
owner = models.ForeignKey('auth.User', related_name='sub-snippets', on_delete=models.CASCADE)
highlighted = models.TextField()
class Meta:
ordering = ['snippet', 'created']
def save(self, *args, **kwargs):
lexer = get_lexer_by_name(self.snippet.language)
linenos = 'table' if self.linenos else False
options = {'title': self.title} if self.title else {'snippet title': self.snippet.title}
formatter = HtmlFormatter(style=self.snippet.style, linenos=linenos,
full=True, **options)
self.highlighted = highlight(self.code, lexer, formatter)

问题是self.snippet.language似乎没有调用实际的Snippet类,因为我收到一个错误,上面写着";ForeignKey的实例没有"language"成员"与self.snippet.titleself.snippet.style相同。

我发现将所有模型放在一个文件中的惯例有点奇怪,我想知道,从编译器POV来看,这是否就是我无法访问Snippet类属性的原因。或者是关于模型在Django/Python中的工作方式?我很想更深入地了解这里发生的事情!

这里有几个问题,所以我一次解决一个。

至于你的模型结构,你可以这样做:

请记住,在python中,当我们将对象传递给类声明时,该类将继承对象的属性、属性和方法。

# Snippet inherits the default django model:
class Snippet(models.Model):
# fields:
title = models.ChardField(...)
...
# this simple method returns the title:
def get_title(self): 
return self.title
# SubSnippet inherits the Snippet class:
class SubSnippet(Snippet):
# fields:
snippet = models.ForeignKey('Snippet', ...)
...

现在我们可以实例化一些这样的实例:

# create a snippet:
snippet = Snippet.objects.create(
title='I am the parent'
)
# create a subsnippet, and assign the above snippet as its 'parent':
subsnippet = SubSnippet.objects.create(
title='I am the child', 
snippet=snippet
)
# accessing fields:
print(subsnippet.title) # prints 'I am the child'
print(subsnippet.snippet.title) # prints 'I am the parent'
print(snippet.title) # prints 'I am the parent'
# using methods:
print(snippet.get_title()) # prints 'I am the parent'
print(subsnippet.get_title()) # prints 'I am the child' 

最新更新