I'm working in Django 1.7 and Postgres, and using the ORM to create some new rows. I am using get_or_create as follows:
p, created = Practice.objects.get_or_create(
code=row[1],
name=row[2],
address1=row[3],
address2=row[4],
address3=row[5],
address4=row[6],
postcode=row[7]
)
But when I try to run this I get:
django.db.utils.IntegrityError: duplicate key value violates unique constraint
DETAIL: Key (code)=(A82057) already exists
What's this about? I thought the point of get_or_create was to only try to create new rows if they didn't already exist.
My model looks like this:
class Practice(TimeStampedModel):
code = models.CharField(max_length=6, primary_key=True, db_index=True)
name = models.CharField(max_length=200)
address1 = models.CharField(max_length=200, null=True, blank=True)
address2 = models.CharField(max_length=200, null=True, blank=True)
address3 = models.CharField(max_length=200, null=True, blank=True)
address4 = models.CharField(max_length=200, null=True, blank=True)
postcode = models.CharField(max_length=9, null=True, blank=True)
def __str__(self):
return self.name
class Meta:
app_label = 'frontend'
ordering = ['name']
Is it something to do with the fact that I've set a manual primary key? I can't see anything in the Django docs about this restriction.
get_or_create attempts to do a get with all of the parameters you pass, not just the PK. So if there is an object with a matching PK but a different postcode, for example, the get will fail so a create will be attempted - but, since you have a manual PK, it will try to create a duplicate one using the data you have passed.
Generally speaking using a non-autoincrementing PK is a bad idea. But if you are just trying to look up against the PK only, use the defaults argument:
p, created = Practice.objects.get_or_create(
code=row[1],
defaults={
'name': row[2],
'address1': row[3],
'address2': row[4],
'address3': row[5],
'address4': row[6],
'postcode': row[7]
})
Related
im getting this error while creating new superuser
Heres the error:
django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_auth_appuser_phone_key"
DETAIL: Key (phone)=() already exists.
I know it is checking for unique phone number while also considering empty phone value and hence giving this error.
my question is how to resolve this
Models.py:
class AppUser(AbstractUser):
user_type = models.PositiveSmallIntegerField(default=1)
class Gender(models.IntegerChoices):
Male = 1, 'MALE'
Female = 2, 'FEMALE'
Other = 3, 'OTHER'
email = models.EmailField(null=True, blank=True)
phone = models.CharField(max_length=15, unique=True)
gender = models.PositiveSmallIntegerField(choices=Gender.choices, null=True, blank=True)
dob = models.DateField(null=True, blank=True)
doa = models.DateField(null=True, blank=True)
#property
def info(self):
from user_auth.serializers import UserSerializer
return UserSerializer(self).data
#property
def token(self):
return RefreshToken.for_user(self)
since I don't have enough reputation to comment, I post my thoughts as an answer.
As seen here Django unique nullable CharField
if you want the phone field to be unique and be empty, you could use phone = models.CharField(max_length=15, unique=True, null=True) so that when it's not provided it results to null instead of '' (empty string).
Since null != null, this might fix it.
These are my two models, when I try to open City page on Django I get an error: "column city.country_id_id does not exist". I don't know why python adds extra _id there.
class Country(models.Model):
country_id = models.CharField(primary_key=True,max_length=3)
country_name = models.CharField(max_length=30, blank=True, null=True)
class Meta:
managed = False
db_table = 'country'
class City(models.Model):
city_id=models.CharField(primary_key=True,max_length=3)
city_name=models.CharField(max_length=30, blank=True, null=True)
country_id = models.ForeignKey(Country, on_delete=models.CASCADE)
class Meta:
managed = False
db_table = 'city'
Because if you construct a foreign key, Django will construct a "twin field" that stores the primary key of the object. The foreign key itself is thus more a "proxy" field that fetches the object.
Therefore you normally do not add an _id suffix to the ForeignKey:
class City(models.Model):
city_id = models.CharField(primary_key=True,max_length=3)
city_name = models.CharField(max_length=30, blank=True, null=True)
country = models.ForeignKey(Country, on_delete=models.CASCADE)
class Meta:
managed = False
db_table = 'city'
It however might be better for unmanaged tables, to specify a db_column=… parameter [Djang-doc] in the ForeignKey:
class City(models.Model):
city_id = models.CharField(primary_key=True,max_length=3)
city_name = models.CharField(max_length=30, blank=True, null=True)
country = models.ForeignKey(Country, db_column='country_id', on_delete=models.CASCADE)
class Meta:
managed = False
db_table = 'city'
With this parameter you make it explicit how the column is named at the database side.
this is due to Django's behind the scenes magic.
The fields documentation is very clear about that and I highly recommend you read the Foreign Key section in the link below:
https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ForeignKey
Basically, when you want to access the Country reference in the if a City instance, you would do it like this:
city.country_id
I also recommend another naming convention for your Foreign Key fields. Instead of <modelname>_id = models.ForeignKey... just call it <modelname> = models.ForeignKey...
Hope this helps, happy coding
First, here are my models. Each string has from 1 up to 3 performers, each performer linked to several strings:
class Performer(models.Model) :
name = models.CharField(max_length=60, default="None")
description = models.TextField(null=True, default=None)
class String(models.Model) :
index = models.IntegerField(null=True, default=None)
step = models.IntegerField(null=True, default=None)
process = models.CharField(max_length=100,null=True, default=None)
description = models.TextField(null=True, default=None)
performer = models.ForeignKey(Performer, related_name='performer', on_delete=models.CASCADE, null=True, default=None)
performer2 = models.ForeignKey(Performer, related_name='performer2', on_delete=models.CASCADE, null=True, default=None)
performer3 = models.ForeignKey(Performer, related_name='performer3', on_delete=models.CASCADE, null=True, default=None)
I need to make set of all Strings related to single performer. However, if I try to use string_set to get all Strings where any of the Performer foreign keys point to that string like so:
p = Performer.objects.get(name="smth")# so p is a performer object
s = p.string_set.all()
I get this issue:
AttributeError: 'Performer' object has no attribute 'string_set'
Also I've tryed to use filters with related name, but this gives me the same error. Is there a way to get a _set based off of one of any foreign key fields that all point to the same type?
By providing related_name in each of performer, performer2, performer3 relations you override the default related_name linking from Performer class which would be string_set. Now to get the String for each of these relations you would have to get them like the following:
p = Performer.objects.get(name="smth")# so p is a performer object
p.performer.all() #first one which would actually be a queryset
p.performer1.all() #second one which would actually be a queryset
p.performer2.all() #third one which would actually be a queryset
This would be true only if you have single String and single Performer related to each other but you should keep in mind that query like p.performer1.all() can actually return 2 or more String objects which would have a relation with this one Performer. This would make things even more cumbersome.
Keep in mind that the ForeignKey creates one-to-many relation...
The models structure you provide would have issues with doing filtering you want. The better model design would look like the following:
class Performer(models.Model) :
name = models.CharField(max_length=60, default="None")
description = models.TextField(null=True, default=None)
strings = models.ManyToManyField(String, related_name='performers')
class String(models.Model) :
index = models.IntegerField(null=True, default=None)
step = models.IntegerField(null=True, default=None)
process = models.CharField(max_length=100,null=True, default=None)
description = models.TextField(null=True, default=None)
This design would allow you to execute:
p = Performer.objects.get(name="smth")# so p is a performer object
s = p.strings.all()
Env: Django 1.8.11 + Postgis
I'm adding some ForeignKeys on a MyModel.
The models pointed are in another schema ("cartography").
makemigrations
no errors
migrate
One error. Can't create the constraint because the generated name.
But I'm adding 10 fields, really similar between them. Only one is giving that stupid error.
I can't specify the constraint name anywhere.
class myModel(models.Model)
zps_calculated = models.ForeignKey( Cartography_zps, verbose_name="zps_calcolato", null=True, blank=True, on_delete=models.SET_NULL)
zsc_sic_sir_calculated = models.ForeignKey( Cartography_zsc_sic_sir, verbose_name="zsc_sic_sir_calcolato", null=True, blank=True, on_delete=models.SET_NULL)
manyothersdata = "xxx"
That is the slice of code generated from sqlmigrate (to inspect the code the migration generate).
As you see the name of the constraint is the error.
1 on 10 fields is giving the error
CREATE INDEX "segnalazioni_f38ba181" ON "segnalazioni" ("zps_calculated_id");
ALTER TABLE "segnalazioni" ADD CONSTRAINT "se_zps_calculated_id_6844dce0603174b2_fk_"cartography"."zps"_id" FOREIGN KEY ("zps_calculated_id") REFERENCES "cartography"."zps" ("id") DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "segnalazioni_eb52e53f" ON "segnalazioni" ("zsc_sic_sir_calculated_id");
ALTER TABLE "segnalazioni" ADD CONSTRAINT "cc6ce48808e3a5292779a9787d21e5ad" FOREIGN KEY ("zsc_sic_sir_calculated_id") REFERENCES "cartography"."zsc_sic_sir" ("id") DEFERRABLE INITIALLY DEFERRED;
That is the name giving the error: "se_zps_calculated_id_6844dce0603174b2_fk_"cartography"."zps"_id"
I think should be something like:
"6844dce0603174b2..."
the model NOT giving the error:
class Cartography_zsc_sic_sir(models.Model):
id = models.AutoField(primary_key=True)
slug = models.CharField(max_length=40, blank=True, null=True)
nome = models.CharField(max_length=60, blank=True, null=True)
the_geom = models.MultiPolygonField(srid=23032, blank=True, null=True )
objects = models.GeoManager()
class Meta:
managed = False
db_table = '"cartography"."zsc_sic_sir"'
verbose_name = 'Cartography - zsc_sic_sir'
verbose_name_plural = 'Cartography - zsc_sic_sir'
ordering = ["id","slug"]
def __unicode__(self):
return self.nome
that is the model giving the error:
class Cartography_zps(models.Model):
id = models.AutoField(primary_key=True)
slug = models.CharField(max_length=40, blank=True, null=True)
the_geom = models.MultiPolygonField(srid=23032, blank=True, null=True )
objects = models.GeoManager()
class Meta:
managed = False
db_table = '"cartography"."zps"'
verbose_name = 'Cartography - ZPS'
verbose_name_plural = 'Cartography - ZPS'
ordering = ["id","slug"]
def __unicode__(self):
return self.slug
Going further I'm investigating in Django code, backwards.
The
' %s ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s (%s)%s;' %
is in
/django/db/backends/base/creation.py row 180
using that
qn = self.connection.ops.quote_name
that SHOULD be the %s constraint name value:
qn(truncate_name(r_name, self.connection.ops.max_name_length()))
Anyone have an hint to help me?
I'm gonna look what qn does.
https://github.com/django/django/releases/tag/1.8.11
The problem was the attribute name (but I still dunno why):
zps_calculated = models.ForeignKey( Carto...
I renamed it to
zpsasd_calculated = models.ForeignKey( Carto
and the generated constraint name changed to (sqlmigrate):
a326518e5e22b0c2c1251e5bbb331adb
Wow!
Renamed the attribute zpsasd_calculated to zps_calculated, with another migration.
Worked.
Next time I will migrate with custom SQL
https://www.ralphlepore.net/custom-foreign-key-constraints-with-django/
This is are my models i want to relate. i want for collection to appear in the form of occurrence.
class Collection(models.Model):
id = models.AutoField(primary_key=True, null=True)
code = models.CharField(max_length=100, null=True, blank=True)
address = models.CharField(max_length=100, null=True, blank=True)
collection_name = models.CharField(max_length=100)
def __unicode__(self):
return self.collection_name
class Meta:
db_table = u'collection'
ordering = ('collection_name',)
class Occurrence(models.Model):
id = models.AutoField(primary_key=True, null=True)
reference = models.IntegerField(null=True, blank=True, editable=False)
collection = models.ForeignKey(Collection, null=True, blank=True, unique=True),
modified = models.DateTimeField(null=True, blank=True, auto_now=True)
class Meta:
db_table = u'occurrence'
Every time i go to check the Occurrence object i get this error
TemplateSyntaxError at /admin/hotiapp/occurrence/
Caught an exception while rendering: column occurrence.collection_id does not exist
LINE 1: ...LECT "occurrence"."id", "occurrence"."reference", "occurrenc..
And every time i try to add a new occurrence object i get this error
ProgrammingError at /admin/hotiapp/occurrence/add/
column occurrence.collection_id does not exist
LINE 1: SELECT (1) AS "a" FROM "occurrence" WHERE "occurrence"."coll...
What am i doing wrong? or how does ForeignKey works?
The problem is that you have not updated your database table definition since adding the ForeignKey. syncdb doesn't do this for you, as the documentation clearly states. You need to update the SQL manually, or use a tool like South.
Are you sure you mean
collection = models.ForeignKey(Collection, null=True, blank=True, unique=True),
Nullable and Unique? This may not be possible in some databases.
Generally, the unique constraint doesn't seem to make much sense here.
Are you trying to force a 1-to-1 relationship? Use the OneToOneField. http://docs.djangoproject.com/en/1.1/ref/models/fields/#django.db.models.OneToOneField