Costantin Costantin -4 years ago 166
Python Question

'tuple' object has no attribute - Django

I'm trying to save some data to my database, but I keep getting the error:

'tuple' object has no attribute 'view_id
I think that somehow I'm getting the object wrongly from my db.

class GoogleProperty(models.Model): # Settings for each single site, a user can have many!
user = models.CharField(max_length=200) # Owner of site
google_email = models.EmailField(max_length=200)
profile_id = models.CharField(max_length=200) # Needed to delete users, but should be removed!

property_name = models.CharField(max_length=200, blank=True, null=True)
property_id = models.CharField(max_length=200, blank=True, null=True)
property_url = models.CharField(max_length=200, blank=True, null=True)

view_id = models.CharField(max_length=200)

def __str__(self):
return str(self.property_url)

def some_function(requests):

if len(list_of_views)==1: # Save to DB and call it a day
view_name = list_of_views[0]['name']
view_id = list_of_views[0]['id']
print(view_id) # 123823290

# Save View to DB
obj, created = GoogleProperty.objects.get_or_create(google_email=current_user, defaults={'view_id': view_id})
if not created:
obj.view_id = view_id
objx = GoogleProperty.objects.get_or_create(google_email=current_user)
print(objx) # (<GoogleProperty: None>, False)
objx.view_id = view_id
return HttpResponse(request, '/ga_app/report.html', {'view_id':view_id})

else: # Many Views, ask which one they want to track
Do something

edit added traceback:

File "/my-path/", line 212, in select_view
objx.view_id = view_id
AttributeError: 'tuple' object has no attribute 'view_id'

I've put as side note the results of the
Also, in some parts of my code I add the
defaults={'view_id': view_id}
is that really needed? If so why?

P.s. I tried both codes that commented out and the one not commented out.

Answer Source

You had the correct approach commented out, why? get_or_create returns a tuple of the form (object, created [boolean]).

What you'd want to do is split out the result of that command:

objx, created = GoogleProperty.objects.get_or_create(google_email=current_user)

Then you can do:

if not created:
    objx.view_id = view_id
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download