T
T
Tinord2018-07-07 17:04:40
Django
Tinord, 2018-07-07 17:04:40

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')

Second:
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)

You need to match between name and author.
Made filtering in views by auth_user from the first model, got all the users on which the user is subscribed. Now I need to take away posts from them, but these two models are not related.
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

2 answer(s)
S
Sergey Tikhonov, 2018-07-08
@tumbler

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()

T
Tim, 2018-07-21
@darqsat

And ManyToMany won't suit you?
It is possible to bring something into one model, what into another. Or I don't get the point.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question