我有2个类Snippet,评论。
错误:当我尝试创建一个片段对象时,始终使用默认评论对象创建评论对象,而不是我指定的评论对象。
s = Snippet()
s.comm.title = "Jello"
s.save()
这不起作用:
ss = Snippets.objects.all()[0].comm.title
返回"默认标题"不是" Jello"。
class Comment(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(
max_length=100,
blank=True,
default='default comment')
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES,
default='python',
max_length=100)
style = models.CharField(choices=STYLE_CHOICES,
default='friendly',
max_length=100)
comm = Comment()
def save(self, *args, **kwargs):
self.comm.save()
super(Snippet, self).save(*args, **kwargs)
答案 0 :(得分:1)
您应该将models.ForeignKey
用于comm
模型中的Snippet
字段。您可以在此链接中详细了解models.ForeignKey。
因此,您的Snippet
模型看起来应该是这样的
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES,
default='python',
max_length=100)
style = models.CharField(choices=STYLE_CHOICES,
default='friendly',
max_length=100)
comm = models.ForeignKey(Comment)
def save(self, *args, **kwargs):
self.comm.save()
super(Snippet, self).save(*args, **kwargs)