Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'tuple' object has no attribute - Django

Tags:

python

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.

Models.py

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)

Views.py

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
      dic_views[view_name]=view_id

      # 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
        obj.save()
      '''
      objx = GoogleProperty.objects.get_or_create(google_email=current_user)
      print(objx)    # (<GoogleProperty: None>, False)
      objx.view_id = view_id
      objx.save
      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/views.py", 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 print() function. 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.

like image 995
Costantin Avatar asked Jul 25 '26 15:07

Costantin


1 Answers

You had the correct approach commented out, why?

https://docs.djangoproject.com/en/1.11/ref/models/querysets/#get-or-create 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
    objx.save()
like image 107
mechanical_meat Avatar answered Jul 27 '26 04:07

mechanical_meat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!