无法更新Django中的模型多对多关系。出现一个错误,指出模型字段未定义。

huangapple go评论68阅读模式
英文:

Not able to update models ManyToMany relationship django. getting an error saying the models field has not been defined

问题

我只翻译代码部分,如下所示:

我只翻译代码部分如下所示

i'm just confused or tired on this one. when this code runs it doesn't always remove or add, and when it does it will not update the like count. As i see the code, when the user is found in the liked value it should remove the user and decrease the likes and visa versa, it does not seem to do that. I also only seem to be able to have 1 like across all pictures, so i would have to remove one like and add to another, again this seems to all happen randomly. 

def liked_pic(request):
    pdb.set_trace()
    if request.method == 'POST':
        pic = Pictures.objects.get(id=request.POST.get('pic_id'))
        user = UserModel.objects.get(email=request.user)
        liked = Pictures.objects.filter(likes=user).exists()
        print(pic.likes, liked)
        if liked:
            pdb.set_trace()
            pic.likes.remove(user)
            pdb.set_trace()
            pic.save()
        if not liked:
            pdb.set_trace()
            pic.likes.add(user)
            pic.save()
        picturecount = Pictures.objects.filter(likes).count()
        data = {'json_pic_id': pic.id,'likes': picturecount, 'user':liked}
        return JsonResponse(data)
        return HttpResponseRedirect('home')


class Pictures(models.Model):
    image = models.ImageField(upload_to='static/dataset/')
    author = models.ForeignKey(UserModel,on_delete=models.CASCADE)
    likes = models.ManyToManyField(UserModel,default=False,blank=True,related_name='likes')       
    description = models.CharField(default=False,max_length=200)


class UserModel(AbstractBaseUser,PermissionsMixin):
    sys_id = models.AutoField(primary_key=True, blank=True)
    email = models.EmailField(max_length=127, unique=True, null=False, blank=False)
    username = models.CharField(max_length=30, unique=True)

    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    objects = MyUserManager()

    USERNAME_FIELD = "email"
    # REQUIRED_FIELDS must contain all required fields on your User model,
    # but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.
    REQUIRED_FIELDS = ['is_staff']
英文:

i'm just confused or tired on this one. when this code runs it doesn't always remove or add, and when it does it will not update the like count. As i see the code, when the user is found in the liked value it should remove the user and decrease the likes and visa versa, it does not seem to do that. I also only seem to be able to have 1 like across all pictures, so i would have to remove one like and add to another, again this seems to all happen randomly.

    def liked_pic(request):
pdb.set_trace()
if request.method == 'POST':
pic = Pictures.objects.get(id=request.POST.get('pic_id'))
user = UserModel.objects.get(email=request.user)
liked = Pictures.objects.filter(likes=user).exists()
print(pic.likes, liked)
if liked:
pdb.set_trace()
pic.likes.remove(user)
pdb.set_trace()
pic.save()
if not liked:
pdb.set_trace()
pic.likes.add(user)
pic.save()
picturecount = Pictures.objects.filter(likes).count()
data = {'json_pic_id': pic.id,'likes': picturecount, 'user':liked}
return JsonResponse(data)
return HttpResponseRedirect('home')
class Pictures(models.Model):
image = models.ImageField(upload_to='static/dataset/')
author = models.ForeignKey(UserModel,on_delete=models.CASCADE)
likes = models.ManyToManyField(UserModel,default=False,blank=True,related_name='likes')       
description = models.CharField(default=False,max_length=200)
class UserModel(AbstractBaseUser,PermissionsMixin):
sys_id = models.AutoField(primary_key=True, blank=True)
email = models.EmailField(max_length=127, unique=True, null=False, blank=False)
username = models.CharField(max_length=30, unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
objects = MyUserManager()
USERNAME_FIELD = "email"
# REQUIRED_FIELDS must contain all required fields on your User model,
# but should not contain the USERNAME_FIELD or password as these fields will always be prompted for.
REQUIRED_FIELDS = ['is_staff']
pdb trace-----------------
System check identified no issues (0 silenced).
January 06, 2020 - 09:50:49
Django version 3.0, using settings 
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
**accounts.UserModel.None False**
(Removed computer path information)
**-> pic.likes.add(user)**
(Pdb) continue
[06/Jan/2020 09:51:05] "POST /liked/ HTTP/1.1" 200 44
[06/Jan/2020 09:51:23] "GET /home/ HTTP/1.1" 200 3141
[06/Jan/2020 09:51:23] "GET /media/static/dataset/00000016.png HTTP/1.1" 200 184935
**accounts.UserModel.None True**
(Removed computer path information)
-> **pic.likes.remove(user)**
(Pdb)
(Pdb) continue
-> pic.save()
(Pdb) continue
[06/Jan/2020 09:51:52] "POST /liked/ HTTP/1.1" 200 44

答案1

得分: 0

不了解应用程序的更多细节,我认为您的逻辑有点错误(显然否则您就不会有问题)。如果您逐步查看您的liked_pic代码,您正在执行以下操作:

  1. 获取用户喜欢的图片
  2. 获取已登录用户
  3. 获取用户喜欢的所有图片
  4. 如果用户喜欢了任何图片,则从此图片中取消喜欢
  5. 如果用户没有喜欢,然后将喜欢添加到当前图片

我认为您可能需要将您的liked行更改为类似以下内容:

liked = Pictures.objects.filter(id=request.POST.get('pic_id'), likes=user).exists()

更具体地说,您需要检查用户是否喜欢了那张图片,而不是所有图片。希望这有所帮助。

英文:

Without knowing more details about the app, I think your logic is slightly off (obviously otherwise you wouldn't have a problem). If you step through your liked_pic code you're doing the following:

  1. Get me the picture the person liked
  2. Get me the logged in user
  3. Get me ALL pictures the user liked
  4. If the user liked ANY picture, then remove the like from this one picture
  5. If the user has ZERO likes, then add the like to the current picture

I think you might need to change your liked line to something like this:

liked = Pictures.objects.filter(id=request.POST.get('pic_id'), likes=user).exists()

More specifically, you need to check if the user has liked that one picture, not all pictures. Hope that helps.

huangapple
  • 本文由 发表于 2020年1月6日 22:03:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613509.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定