[Django]-Django get_or_create return error: 'tuple' object has no attribute

55👍

get_or_create does not just return the object:

Returns a tuple of (object, created), where object is the retrieved or created object and created is a boolean specifying whether a new object was created.

In your case d has been assigned this tuple instead of the object you expected, so you get the attribute error. You can fix your code by changing it to:

d, created = DiaSemana.objects.get_or_create(dias=diaSemana)

The following two lines look unnecessary to me. The get_or_create call above ensures that d.dias=diaSemana, so there’s no need to assign it again. There’s probably no need to call save either.

d.dias = diaSemana;
d.save()

3👍

instead of this:

dias = models.CharField(max_length=20, choices=DIAS_CHOICES) 

do:

dias = models.CharField(max_length=20, choices=DIAS_CHOICES)[0]

as @Alasdair said, the first one in the tuple is the object

2👍

Documentation clearly says that get_or_create returns tuple (object, created) – and this is exactly error you are seeing.
https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create

👤jasisz

Leave a comment