Reputation: 485
I have a query using 3 tables. The law
, article
and marked
.
I have a website where the user can choose one law
to read all the articles
. For each article, the user can marked it or type some description for this article.
The marker
and description
is saved on the marked
table. So, when the user open his law again, all his markations and descriptions will be loaded.
The problem is that in my query, I dont know how show the descriptions and markations of the user logged in. My query is showing the descriptions and markations for all users registered in marked table.
An example of marked table content:
id is_marked description article_id law_id user_id
"0" "0" "test1" "1100" "3" "1"
"1" "0" "test2" "1102" "3" "1"
If I access the law = 3
with the user_id =2
, all the description of the user_id = 1
is showing.
My query:
law = get_object_or_404(Law, pk=pk)
articles = Article.objects.filter(law=pk)
articles = (
Article
.objects
.filter(law=pk)
.annotate(
is_marked=Exists(
Marked
.objects
.filter(
article_id=OuterRef('id'),
usuario=request.user,
is_marked=1,
)
)
)
.annotate(
description=(F('markedLaw__description'))
).order_by('id')
My model:
class Law(models.Model):
name = models.CharField('Nome', max_length=100)
description = models.TextField('Description', blank = True, null=True)
class Article(models.Model):
article = models.TextField('Article')
id_article_law = models.IntegerField('Article Law', blank=True, null=True)
law = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Law', related_name='Articles')
class Marked(models.Model):
law = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Law', related_name='markedArtigos')
Article = models.ForeignKey(Article, on_delete=models.CASCADE, verbose_name='Article', related_name='markedLaw')
usuario = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='markedUsuario', related_name='markedUsuario')
is_marked = models.BooleanField('Está Marcado?', blank=True, default=False)
description = models.TextField('Descrição', blank = True, null=True)
Upvotes: 0
Views: 32
Reputation: 2568
You could create a template tag filter, that will receive the logged in user and article and filter the Marked model.
On this case you would be dealing with it at the template level, no need to do annotations.
Here is the reference: https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/
Upvotes: 1