Home > Software engineering >  Django - Query by foreign key in views
Django - Query by foreign key in views

Time:02-26

I am trying to make a button on the post that when a user cliks on it, is requesting to be added to the post as an attendance and then, the author of the post has to approve that request.

Models.py

class Attending(models.Model):
    is_approved = models.BooleanField(default=False)
    attending = models.ManyToManyField(User, related_name='user_event_attending')
class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField(blank=True)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    attending = models.ForeignKey(Attending, on_delete=models.CASCADE, verbose_name='atending', null=True)

My problem here is that every time I writte a query for the button is giving me erros and I couldn`t figure it out how to get the reverse of the foreign key.

This is my code on my views.py

def request_event(request, pk):
    previous = request.META.get('HTTP_REFERER')
    try:
        query = Attending.objects.get(pk=pk)
        request_attending = query.post_set.add(request.user)
        messages.success(request, f'Request sent!')
        return redirect(previous)
    except query.DoesNotExist:
        return redirect('/')

Thank you very much for your help in advance!

CodePudding user response:

This: query.post_set is just relationship. You cannot call method add just like that. You can add to ManyToMany relation and I believe you want to add user to Attending.attending field, not directly to Post object. Change that to:

...
query = Attending.objects.get(pk=pk)
query.attending.add(request.user)
messages.success(request, f'Request sent!')
....

| Update |

I think you should consider rearraning your relationships. If I understand your plan, you should go this way:

class Attending(models.Model):
    ...
    attendant = models.ForeignKey(User, related_name='events_attending', on_delete=models.CASCADE)
    post = models.ForeignKey('Post', on_delete=models.CASCADE)

class Post(models.Model):
    ...
    author = models.ForeignKey(User, on_delete=models.CASCADE)

For one Post object there can be many Attending objects, then you can use relations like that:

att = Attending.objects.first()
att.post                         # get related Post object from ForeignKey | there is only one

post = Post.objects.first()
post.attending_set.all()         # get all related Attending objects

Post.objects.get(attending=att)  # get Post object that the Attending object have in ForeignKey field

user = User.objects.first()
user.post_set.all()              # get all Post objects that User is author in
user.events_attending.all()      # get all related Attending objects

For more check Django Docs.

  • Related