Answer the question
In order to leave comments, you need to log in
How to make a match between the two models?
Hello.
Such question: there are two models which are not connected among themselves.
First, it is formed from Post requests to add users:
class Subscriber(models.Model):
name = models.CharField(max_length=50, null=True)
user_id = models.PositiveIntegerField()
auth_user = models.CharField(max_length=50)
creation_date = models.DateTimeField(verbose_name='creation date')
class BlogPost(models.Model):
title = models.CharField(max_length=200)
text = models.TextField(default='')
author = models.ForeignKey(User, on_delete=models.CASCADE, max_length=50)
created_date = models.DateTimeField(
default=timezone.now)
class GetSubscribers(TemplateView):
template_name = 'pages/subscriptions.html'
def get_context_data(self, **kwargs):
context = super(GetSubscribers, self).get_context_data(**kwargs)
context['users'] = models.Subscriber.objects.filter(auth_user=self.request.user)
context['posts'] = models.BlogPost.objects.all
return context
Answer the question
In order to leave comments, you need to log in
If no tricks, then no way. Since Subscriber simply stores user_id instead of ForeignKey(User), Django does not know that there is a foreign key relationship between Subscriber and BlogPost. Accordingly, the ORM cannot build the corresponding query.
To do it right, the Subscriber must have two ForeignKey(User) - one for the subscriber and one for the author. Then all the authors of the user can be obtained like this:[s.author for s in user.subsriber_set.all()]
If you do not change the data schema, then you can write a direct SQL query via User.objects.raw()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question