不添加一对多关系

时间:2018-10-04 20:44:40

标签: django django-models

我上课

class Read(models.Model):
   class Meta:
    verbose_name_plural = 'reads'

   id=models.AutoField(primary_key=True);
   name = models.CharField(max_length=30, null=True);
   owner_reader = models.ForeignKey(User, related_name='owner_reader', null=False, blank=True,on_delete=models.PROTECT)  # тот, кто прочитал
   articles_readed = models.ManyToManyField(Article, null=False, related_name='articles_readed')  # те, на кого он пдписалса

并希望添加文章以阅读项目:

def mark_readed(request,id):
    #id -article id
    user =request.user # подписант
    try:
        reader1 = Read.objects.get(name='test',owner_reader=request.user)  
    except Read.DoesNotExist:
        reader1 = Read.objects.create(name='test',owner_reader=request.user)
    article = Article.objects.get(pk=id) 
    reader1.articles_readed.add=article
    reader1.save();
    return main(request)

但是结果,我只阅读了wisout文章。

1 个答案:

答案 0 :(得分:1)

如果我正确地理解了这个问题,那么您正在尝试将文章添加到“ articles_readed”多对多字段中。

根据django的文档(https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/),您应该使用add()方法将读取的对象与文章相关联。

因此,您应将reader1.articles_readed.add=article替换为reader1.articles_readed.add(article)。此外,添加文章后,您无需调用read save()方法。

希望这会有所帮助!