python - 我无法根据对另一个模型的一对一字段引用中的字段进行过滤

标签 python django postgresql

我希望能够在 Student 中过滤电子邮件。 就像我这样做:Student.objects.get(email="k@gmail.com")

学生有 email="k@gmail.com"的行被返回。

我试过使用以下版本,但出现了这个错误:

ValueError: invalid literal for int() with base 10: 'kkk@gmail.com'

我也试过打印出类型:

View .py

for l in ll:
        print(type(l.email.email)). # got <class 'str'>
        print(type(l.language_to_learn))

print(type(l.email)) # got <class 'users.models.CustomUser'>


def profile_list(request):
    profile=Student.objects.get(email=request.user.email)
    return render(request,'view_profile.html',{'profile':profile})

模型.py

class Student(models.Model):
          email=models.OneToOneField(CustomUser,on_delete=models.CASCADE,primary_key=True,)
      language_to_learn=models.CharField(max_length=20,choices=Language_Choices,default='English',)
    REQUIRED_FIELDS=['language_to_learn',]

class CustomUser(AbstractUser):
    username = None
    email = models.EmailField('email address' ,unique=True,blank=False, null=False) 
    USERNAME_FIELD = 'email'
    fullname=models.CharField('Full name',max_length=50,null=True)
    REQUIRED_FIELDS = [] # removes email from REQUIRED_FIELDS
    objects = UserManager()

最佳答案

首先,您应该将 models.py email 字段更改为 user 而不是 email 以避免混淆。

class Student(models.Model):      
  user=models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True)

然后查询like。

profile=Student.objects.get(user__email=request.user.email)

If you don't want to change the field name. Then you should do like below coz email is a field of related OneToOneField of CustomUser.

profile=Student.objects.get(email__email=request.user.email)

关于python - 我无法根据对另一个模型的一对一字段引用中的字段进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57061387/

相关文章:

python - Python 与 Ruby 中的 RSA 加密

python - 每当 mysql 服务重新启动时,uwsgi 如何重新建立与远程 mysql 数据库的连接

django - 使用 Queryset API 按组计算总和

java - PostgreSQL, hibernate : Moving contents of db to text file/XML file for storage purposes

mysql - 是否仍在使用 XA/JTA 事务?

python - 仅当列没有值时,Pandas DataFrame 才从另一个数据帧更新

django model.charfield - unicode 或非 unicode

python - Django查询集在查询中获取空值

json - 如何将 to_jsonb 用作 row_to_jsonb?关于 "how much"的详细信息在哪里?

Python:如何将 Shutil.copy() 与 unicode 文件名一起使用