class A(models.Model):
profile = models.OneToOneField(
"profile.Profile",
related_name="notification_setting",
unique=True,
on_delete=models.CASCADE,
)
email_flag = models.TextField(null=True, default="")
other fields...
It’s first time to create but SOMETIMES it raises IntegrityError. Not always.
It makes me crazy.
A models’s fields has default value.
I use A.objects.create(profile=profile). Does it matter?
Please share the view as well and the fault trace back from the terminal.
At first glance, if you’re creating a OneToOne connection to a Profile model, the first parameter to the profile model field should not be profile.profile, but only Profile (the name of the model you are making a OneToOne connection to).
Also, set the unique attribute on the a field in the Profile model instead, not in the A model. Since you have a OneToOne connection to the Profile model, there will be exactly one mapping to each Profile instance from the A model.
This should solve the integrity error, but I need to see the actual error and you view as well.
The IntegrityError error usually occurs when there are problems with data integrity in the database. In your model, the profile field is defined as OneToOneField, which means that each Profile object can only be associated with one A object. If you try to associate the same Profile object with more than one A object, this can cause to an IntegrityError error.