1
votes

Upon creating a new object from a model, my site is supposed to redirect to a detailed view of that object. However, it keeps returning the error message: "invalid literal for int() with base 10: 'The name granted to my object'". I've looked online and seen that often people receive this error when they have parsed some digits as a string rather than an int or float, but in my case the value identified is clearly intended to be a string.

I've examined the error message and my code is detailed below. Python appears to be taking issue with the self variable, which I have used to filter the number of objects from another model that are aggregated. Some context: This is a method within my 'accelerator' model intended to determine the average rating of the accelerator object by aggregating the overall rating from each review of that particular accelerator. In my review model the subject field is a foreign key to the accelerator model.

class Accelerator(models.Model):
    name = models.CharField(max_length=100)
    website = models.CharField(max_length=100)
    locations = models.CharField(max_length=100)
    bio = models.TextField()
    sector_focus = models.CharField(max_length=100)
    stage = models.CharField(max_length=100)
    deal = models.CharField(max_length=200)
    duration = models.CharField(max_length=100)
    avg_rating = models.DecimalField(decimal_places=2, max_digits=3)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default='admin')
    logo = models.ImageField(default='default.jpg', upload_to='logos')

    def __str__(self):
        return self.name

    # Function to configure correct URL once new model instance has been created
    def get_absolute_url(self):
        return reverse('accelerator_detail', kwargs={'pk': self.pk})

    @property
    def avg_rating(self):
        result = Review.objects.filter(subject=self.name).aggregate(avg_rating=Avg('overall')).avg_rating
        return result if result > 0 else 0

class Review(models.Model):
    RATINGS = (
        ('1', '1'),
        ('2', '2'),
        ('3', '3'),
        ('4', '4'),
        ('5', '5'),
    )
    subject = models.ForeignKey(Accelerator, on_delete=models.CASCADE, blank=False)
    author = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, default='admin')
    feedback = models.TextField(blank=False)
    date_posted = models.DateTimeField(default=timezone.now)
    mentorship = models.CharField(choices=RATINGS, blank=False, max_length=1)
    hiring = models.CharField(choices=RATINGS, blank=False, max_length=1)
    community = models.CharField(choices=RATINGS, blank=False, max_length=1)
    fundraising = models.CharField(choices=RATINGS, blank=False, max_length=1)
    corporate_dev = models.CharField(choices=RATINGS, blank=False, max_length=1)
    overall = models.DecimalField(decimal_places=2, max_digits=3)

    def __str__(self):
        return self.subject

    def get_absolute_url(self):
        return reverse('review_detail', kwargs={'pk': self.pk})

    def save(self, *args, **kwargs):
        # set the overall field when the model is saved
        self.overall = self.mentorship + self.hiring + self.community + \
            self.fundraising + self.corporate_dev / 5
        super(Review, self).save(*args, **kwargs)

enter image description here

My traceback:

Traceback (most recent call last):
  File "/home/samalty/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/mnt/c/Users/Sam/CSA/csa_project/reviews/views.py", line 36, in accelerator_detail
    return render(request, 'reviews/accelerator_detail.html', context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 171, in render
    return self._render(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/loader_tags.py", line 150, in render
    return compiled_parent._render(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 163, in _render
    return self.nodelist.render(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/loader_tags.py", line 62, in render
    result = block.nodelist.render(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 937, in render
    bit = node.render_annotated(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 904, in render_annotated
    return self.render(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 987, in render
    output = self.filter_expression.resolve(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 671, in resolve
    obj = self.var.resolve(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 796, in resolve
    value = self._resolve_lookup(context)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/template/base.py", line 837, in _resolve_lookup
    current = getattr(current, bit)
  File "/mnt/c/Users/Sam/CSA/csa_project/reviews/models.py", line 29, in avg_rating
    result = Review.objects.filter(subject=self.name).aggregate(avg_rating=Avg('overall')).avg_rating
  File "/home/samalty/.local/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/db/models/query.py", line 892, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/home/samalty/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1290, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1318, in _add_q
    split_subq=split_subq, simple_col=simple_col,
  File "/home/samalty/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1251, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/db/models/lookups.py", line 20, in __init__
    self.rhs = self.get_prep_lookup()
  File "/home/samalty/.local/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 115, in get_prep_lookup
    self.rhs = target_field.get_prep_value(self.rhs)
  File "/home/samalty/.local/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 966, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: 'Founders Factory'
2
Please, post your models.py codeHigor Rossato
self is not the problem here. Please post the traceback, as well as the Review model and whatever model self refers to.Daniel Roseman

2 Answers

0
votes

Your issue is that you are using name as the lookup value, which is not expected by the foreign key.

(Note also that aggregate returns a dict, and avg_rating is a key in that dict, not an attribute on an instance.).

So you should do:

result = Review.objects.filter(subject=self).aggregate(avg_rating=Avg('overall'))['avg_rating']

Or even better:

result = self.review_set.aggregate(avg_rating=Avg('overall'))['avg_rating']
1
votes

Your filter on your queryset is wrong. You're saying subject=self.name. So basically, you're comparing a ForeignKey (subject) with a string (self.name)

You can do something like this:

    @property
    def avg_rating(self):
        result = Review.objects.filter(subject=self).aggregate(avg_rating=Avg('overall'))
        return result

This will return a QuerySet, empty or not. Then, when looping through it, you can access all the attributes in it including avg_rating.