Django-为什么此模型不创建pk并抱怨相关模型pk的完整性?

时间:2018-07-16 18:06:15

标签: python django django-models

该模型为什么不创建pk并抱怨相关模型pk的完整性?

在创建UserProfile的新实例时,它不是在创建主键。

我正在遵循一对一的说明in this tutorial(这就是@receiver的全部内容)

models.py中包含以下内容:

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    guid = models.UUIDField(null=True)

    @classmethod
    def create(cls, first_name, last_name, email, guid=None):
        user = User.objects.create(first_name=first_name, last_name=last_name, email=email)
        user_profile = cls(user=user, guid=guid) if guid else cls(user=user)
        # user_profile.save()  ## This didn't work..
        return user_profile

    def most_recent_device(self):
        return self.devices.order_by('-pk').first()

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()


class Device(models.Model):
    guid = models.UUIDField(null=True)
    fcm_token = models.CharField(max_length=4096, null=True)
    user_profiles = models.ManyToManyField(UserProfile, related_name='devices')

    def most_recent_user(self):
        return self.user_profiles.order_by('-pk').first()

    @classmethod
    def create(cls, guid=None, fcm_token=None, user_profiles=None):
        self = cls()
        self.save()  ## possibly excessive saving trying to get this to work
        if guid:
            self.guid = guid
        if fcm_token:
            self.fcm_token = fcm_token
        if user_profiles:
            for user_profile in user_profiles:
                self.user_profiles.add(user_profile.user.pk)
        self.save()  ## possibly excessive saving trying to get this to work
        return self

当我创建UserProfile模型的实例时,不会自动创建pk。例如,我将其输入到交互式外壳中:

>>> user_profile = UserProfile.create(
    first_name = 'firstname',
    last_name = 'lastname',
    email = 'firstname.lastname@company.com',
    guid = "ed282e0c-4e9d-404b-ba70-8910ec7fe780"
)

然后,当我访问UserProfile的主键时,我什么也没得到:

>>> user_profile.pk

有趣的是,为用户模型创建了pk IS:

>>> user_profile.user.pk
3

致电user_profile.save()时,出现以下异常:

  

django.db.utils.IntegrityError:唯一约束失败:   Interface_userprofile.user_id

我在做什么错? /发生了什么事?

这是完整的堆栈跟踪:

>>> user_profile.save()
Traceback (most recent call last):
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: Interface_userprofile.user_id

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\base.py", line 729, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\base.py", line 759, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\base.py", line 842, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\base.py", line 880, in _do_insert
    using=using, raw=raw)
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\query.py", line 1125, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Program Files\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1285, in execute_sql
    cursor.execute(sql, params)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Program Files\Python37\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Program Files\Python37\lib\site-packages\django\db\backends\sqlite3\base.py", line 303, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: Interface_userprofile.user_id

2 个答案:

答案 0 :(得分:2)

我怀疑import java.io.PrintStream; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import javax.net.ssl.HttpsURLConnection; public class App{ public static void main(String []args) throws NoSuchAlgorithmException, KeyManagementException{ String https_url = "https://192.168.14.5:8989/books"; String content = "{\"data\":{\"aaa\"}}"; System.setProperty("javax.net.useSystemProxies", "true"); System.setProperty("javax.net.ssl.keyStore", "C:/cert/client_cert.jks"); System.setProperty("javax.net.ssl.keyStorePassword", "testdev"); System.setProperty("javax.net.ssl.trustStore", "C:/cert/server_cert.jks"); System.setProperty("javax.net.ssl.trustStorePassword", "testdev"); System.setProperty("jdk.tls.client.protocals", "TLSv1.2"); System.setProperty("https.protocals", "TLSv1.2"); HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> { return true;}); URL url = new URL(https_url); HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection(); httpsCon.setRequestProperty("Content-Type", "application/json"); httpsCon.setRequestMethod("POST"); httpsCon.setDoOutput(true); PrintStream ps = new PrintStream(httpsCon.getOutputStream()); ps.println(content); ps.close(); httpsCon.connect(); httpsCon.getResponseCode(); httpsCon.disconnect(); } } ,您的instance.profile.save()和在您的教程中related_name='profile'被称为UserProfile的事实引起了混淆。

在本教程中,Profile指模型.profile,但在您的情况下,Profile.profile的{​​{1}}字段。

是您使用user而不是UserProfile吗?

我会尝试:

profile

代替:

user_profile

答案 1 :(得分:1)

问题不在于您的pk。这是因为您要为每个用户创建两次配置文件:一次在您的信号中,一次在您的create方法中。

您不需要信号。删除它。