我的ManyToMany遇到问题。我可以在其中添加对象,但是我很难理解调用数据的请求。这是我的模型。py:
class Parcours(models.Model):
articleList = models.ManyToManyField('Article')
author = models.CharField(max_length=250,blank=True)
class Article(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
fileItem = models.OneToOneField('FileItem', on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
thumbnail = models.ImageField(upload_to='media/static')
category = models.ForeignKey('Category',on_delete=models.CASCADE, null=True, blank=True) #TODO
date = models.DateTimeField(default=timezone.now, verbose_name="Date de Parution")
slug = models.SlugField(max_length=100)
content = models.TextField()
adress = models.CharField(max_length=250,blank=True)
autorisation = models.BooleanField(default=True,verbose_name="Autorisation des commentaires")
这是我的views.py:
@login_required
def profil(request,id):
Myarticle = Article.objects.filter(author=request.user)
All = Article.objects.all()
UserProfil=User.objects.get(id=id)
parkour = Parcours(author=request.user)
parkour.save()
print(parkour.articleList.all())
return render(request, 'blog/profil.html', locals())
每个多对多都需要一位作者。我究竟做错了什么?预先感谢。
答案 0 :(得分:0)
要添加和获取articleList
中的Parcours
,您可以执行以下操作:
parcours = Parcours.objects.create(...)
article = Article.objects.create(...)
parcours.articleList.add(article)
parcours.articleList.all()
<QuerySet [<Article: 1>]>
如果您想让所有Parcours
都使用一个Article
:
article.parcours_set.all()
<QuerySet [<Parcours: 1>]>