4

I am new with django framework struggling to compare value from the database. this are my tables in models.py :

class Post(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE,)
   title = models.CharField(max_length=200)
   content = models.TextField()
   creationDate = models.DateTimeField(auto_now_add=True)
   lastEditDate = models.DateTimeField(auto_now=True)

   def __str__(self):
       return self.title

class Votes(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE,)
   post_id = models.ForeignKey(Post, on_delete=models.CASCADE,)
   up_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)])
   down_vote = models.PositiveIntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)])

   class Meta:
       unique_together = (("user","post_id"),) 

I have data in the vote tabe like this: enter image description here

Now what I want is to check in the above table if 'user_id' and 'post_id' already exists in the Votes tabel's rows if the exist throw a message if not add value on upvote or downvote, i gues everyone understand what i want if not please let me know.

something which i tried was this code:

def chk_table():
    user_id = request.user
    post_id = id
    votes_table = Votes.objects.filter(user_id=user_id, post_id= post_id).exists()
    return votes_table

but this function is checking in hole table not just in just in one row...

Umer
  • 77
  • 1
  • 1
  • 8

2 Answers2

6

Assuming that, in your urls.py

from django.urls import path
from .views import add_vote

urlpatterns = [
    path('post/<int:post_id>/vote/add/', add_vote, name='add-vote'),
]

In your views.py

from django.shortcuts import redirect, render

def add_vote(request, post_id):
    if request.method == 'POST':
        # receive your POST data here
        user_id = request.user.id
        post_id = post_id
        if not Votes.objects.filter(user_id=user_id, post_id=post_id).exists():
            Votes.objects.create(**your_data)
        redirect('your-desired-url')
    else:
        # your logic here

2

I see you already defined unique_together in Meta so you can use try except

from django.db import IntegrityError

try:
    # your model create or update code here
except IntegrityError as e: 
    if 'unique constraint' in e.message:
        # duplicate detected
chamoda
  • 581
  • 5
  • 15
  • thank you for answering i used other method i am not using this because i modified the other errors. – Umer Jun 27 '19 at 20:53