Django多对多关系反向查询
我有两个名为“Author”和“Entry”的模型,定义如下Django多对多关系反向查询,django,django-models,Django,Django Models,我有两个名为“Author”和“Entry”的模型,定义如下 class Author(models.Model): name = models.CharField(max_length=50) email = models.EmailField() msgtoauthor = models.TextField() class Entry(models.Model): blog = models.ForeignKey(Blog) headline = m
class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
msgtoauthor = models.TextField()
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateTimeField()
authors = models.ManyToManyField(Author)
我正在尝试从“条目”访问“Author.msgtoauthor”
我知道,我可以通过
e = Entry.objects.get(authors)
是否可以提取作者id
我知道在后端,Django为作者和条目创建了一个表,但我想从“Entry”中的方法更新“msgtoauthors”
提前谢谢。你是说
for author in my_entry.authors.all():
author.msgtoauth = 'Here is new content'
author.save()
?
Entry.authors返回一个RelatedManager,my_Entry.authors.all是一个QuerySet,返回Author对象。见和
更新。你是说
for author in my_entry.authors.all():
author.msgtoauth = 'Here is new content'
author.save()
?
Entry.authors返回一个RelatedManager,my_Entry.authors.all是一个QuerySet,返回Author对象。见和
更新。如果所有作者获得相同的值,您可以执行以下操作:
entry.authors.update(msgtoauthor='Hey there!')
如果所有作者获得相同的值,您可以执行以下操作:
entry.authors.update(msgtoauthor='Hey there!')
第52行
-干杯
第52行
-干杯试试这个:
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateTimeField()
authors = models.ManyToManyField(Author)
def msgtoat(self, message):
self.authors.update(msgtoauthor=message)
例如,要更新条目,请执行以下操作:
entry.msgtoat('Hello')
试试这个:
class Entry(models.Model):
blog = models.ForeignKey(Blog)
headline = models.CharField(max_length=255)
body_text = models.TextField()
pub_date = models.DateTimeField()
authors = models.ManyToManyField(Author)
def msgtoat(self, message):
self.authors.update(msgtoauthor=message)
例如,要更新条目,请执行以下操作:
entry.msgtoat('Hello')
我在类Entry def msgtoatself:update msgtoauthor中有一个函数,所以我想使用上面的函数为每个作者更新一个特定条目的变量。我不能改变这个函数的类。是的,有点。在我这样做之前,我需要查询作者的id,对吗?我在类条目def msgtoatself:update msgtoauthor中有一个函数,所以我想使用上述函数为每个作者更新该变量,以获得特定条目。我不能改变这个函数的类。是的,有点。在此之前,我需要查询作者的id,对吗?