类型错误:字段 'id' 需要一个数字,但得到 (<Group: customer>, True) DJANGO ERROR

Posted

技术标签:

【中文标题】类型错误:字段 \'id\' 需要一个数字,但得到 (<Group: customer>, True) DJANGO ERROR【英文标题】:TypeError: Field 'id' expected a number but got (<Group: customer>, True) DJANGO ERROR类型错误:字段 'id' 需要一个数字,但得到 (<Group: customer>, True) DJANGO ERROR 【发布时间】:2022-01-22 20:45:10 【问题描述】:

我正在通过一个小项目学习如何使用 Django ...我正在尝试将我的项目连接到 Postgreslq 数据库,但我遇到了这种类型的错误

models.py

from django.db import models
from django.db.models.deletion import SET_NULL
from django.contrib.auth.models import User

class Customer(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)
    profile_pic = models.ImageField(default='profile1.png',null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    
    def __str__(self):
        return self.name

class Tag(models.Model):
    name = models.CharField(max_length=200, null=True)
    
    def __str__(self):
        return self.name 

class Product(models.Model):
    CATEGORY = (
            ('Indoor', 'Indoor'),
            ('Out Door', 'Out Door'),
            ) 
    
    name = models.CharField(max_length=200, null=True)
    prince = models.FloatField(null=True)
    category = models.CharField(max_length=200, null=True, choices=CATEGORY)
    description = models.CharField(max_length=200, null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.name

class Order(models.Model):
    STATUS = (
            ('Pending', 'Pending'),
            ('Out for delivery', 'Out for delivery'),
            ('Delivered', 'Delivered'),
            )
    
    customer = models.ForeignKey(Customer, null=True, on_delete=SET_NULL)
    product = models.ForeignKey(Product, null=True, on_delete=SET_NULL)
    status = models.CharField(max_length=200, null=True, choices=STATUS)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    note = models.CharField(max_length=1000, null=True)

    def __str__(self):
        return self.product.name

signals.py

from django.db.models.signals import post_save
from django.contrib.auth.models import User, Group
from .models import Customer

def customer_profile(sender, instance, created, **kwagrs):
    if created:
        group = Group.objects.get_or_create(name='customer')
        instance.groups.add(group)
        Customer.objects.create(
                user = instance,
                name = instance.username
            )
        print('Profile created.!')

post_save.connect(customer_profile, sender= User)

settings.py

DATABASES = 
    'default': 
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'DEMO_TEST',
        'USER' : 'postgres',
        'HOST': 'localhost',
        'PASSWORD':'Elohim150..',
        'PORT': '5432',
    

追溯

  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
    return super().execute(*args, **options)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle
    self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\models.py", line 163, in create_superuser
    return self._create_user(username, email, password, **extra_fields)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\models.py", line 146, in _create_user
    user.save(using=self._db)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save
    super().save(*args, **kwargs)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\base.py", line 726, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\base.py", line 774, in save_base
    post_save.send(
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send
    return [
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp>
    (receiver, receiver(signal=self, sender=sender, **named))
  File "C:\Users\l\Desktop\django-course\Django(02-09-21)\crm1\accounts\signals.py", line 8, in customer_profile
    instance.groups.add(group)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 950, in add
    self._add_items(
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 1126, in _add_items
    target_ids = self._get_target_ids(target_field_name, objs)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 1073, in _get_target_ids
    target_ids.add(target_field.get_prep_value(obj))
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\fields\related.py", line 977, in get_prep_value
    return self.target_field.get_prep_value(value)
  File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value
    raise e.__class__(
TypeError: Field 'id' expected a number but got (<Group: customer>, True).
    

也许我在“客户”模型中的某个字段存在错误,但我真的百分百不明白错误是什么,因为我没有经验......有人可以告诉我错误吗并向我解释解决方案,这将非常有帮助。 !!

【问题讨论】:

【参考方案1】:

在 django 中获取或创建返回元组。 (对象,已创建)

https://docs.djangoproject.com/en/4.0/ref/models/querysets/#get-or-create

get_or_create(defaults=None, **kwargs)¶ 一种使用给定 kwargs 查找对象的便捷方法(如果您的模型具有所有字段的默认值,则可能为空),如有必要,创建一个。 返回 (object, created) 的元组,其中 object 是检索或创建的对象, created 是一个布尔值,指定是否创建了新对象。

试试这个

def customer_profile(sender, instance, created, **kwagrs):
    if created:
        group, is_created = Group.objects.get_or_create(name='customer')
        if is_created:
            instance.groups.add(Group.objects.get(name='customer'))
        else:
            instance.groups.add(group)
        Customer.objects.create(
                user = instance,
                name = instance.username
            )
        print('Profile created.!')

更多详情请参考https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/

【讨论】:

以上是关于类型错误:字段 'id' 需要一个数字,但得到 (<Group: customer>, True) DJANGO ERROR的主要内容,如果未能解决你的问题,请参考以下文章

类型错误:字段 'id' 需要一个数字,但得到 <django.contrib.auth.models.AnonymousUser object at 0x048C7E90>

字段 'id' 需要一个数字,但得到了 ''

获取 ValueEerror:字段 'id' 需要一个数字,但得到一个 html

字段“id”需要一个数字,但得到了 ObjectId

得到“<Team:jaja>”的错误需要有一个字段“id”的值才能使用这种多对多关系

错误:Note.user 字段类型必须是输出类型,但得到:[object Object]