0

I have these models and I have burnt all the night trying to figure how I could save to Likes table but it won't just work.

class Users(models.Model):
    email = models.EmailField()
    name = models.CharField(max_length=60)

class Posts(models.Model):
    user_id = models.ForeignKey('Users')
    content = models.CharField(max_length=480)

class Likes(models.Model):
    post_id = models.ForeignKey('Posts', related_name='likes_set')
    user_id = models.ForeignKey('Users')
    status = models.IntegerField()

Say user_id1 = 1 and truly exist in the table, post_id11 = 11 and also exist, and this user clicks on this post.

Now I want to save to Likes table and this is what I did;

user = Users.objects.get(id = user_id1)
post = user.posts_set.get(id = post_id11)
try:
    liked = post.likes_set.get(user_id = user_id1)
except Likes.DoesNotExist:
    liked = None
if liked:
    liked.status = F('status') - 1
    liked.save()
    total_likes = liked.status
    return HttpResponse(total_likes)
else:
    post.likes_set.create(user_id = user_id1, post_id = post_id11, status = 1)
    post.likes = F('likes') + 1
    post.save()
    total_likes = post.likes
    return HttpResponse(total_likes)

And this the ERROR: ValueError at /myapp/likeRecorder/ Cannot assign "1": "Likes.user_id" must be a "Users" instance.

I have googled all night trying to solve this. Help!

Yax
  • 2,127
  • 5
  • 27
  • 53

2 Answers2

0

In post.likes_set.create(user_id = user_id1, post_id = post_id11, status = 1) replace user_id = user_id1 with user_id = user, because you defined user before, user = Users.objects.get(id = user_id1).

In terms of assignment Django checks the type of the variable when you give it to manager.create.

Also, you don't have to name your ForeignKey as xxx_id. I think it is not very semantic.

terencezl
  • 69
  • 1
  • 8
  • This didn't work. It returns `Likes matching query does not exist.` – Yax Oct 03 '14 at 04:27
  • In the same line `post_id = post_id11` should be changed to `post_id = post` for the same reason. This way the two ForeignKey's requirements are both satisfied. – terencezl Oct 04 '14 at 05:11
0

The ID attribute for the ForeignKey named foo is named foo_id. Since you've gone and named your FK user_id for... some... "reason", the ID attribute is named user_id_id.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • Thank you but it returns `DoesNotExist at /myapp/likeRecorder/ Likes matching query does not exist.` after changing `user_id` to `user_id_id` and I also tried changing `post_id` to `post_id_id` but error is still the same. – Yax Oct 03 '14 at 04:33
  • Funny enough, I just checked my DB and it is updating as I click on the posts but the code is still returning the error. – Yax Oct 03 '14 at 05:13
  • Why don't you add your error traceback in the question, its hard to understand why this error occured from one line. – ruddra Oct 03 '14 at 05:52