CodexBloom - Programming Q&A Platform

Django: Unhashable Type scenarios When Using a Custom Model in a List Comprehension

πŸ‘€ Views: 389 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-12
django queryset list-comprehension Python

I'm following best practices but I'm working on a project and hit a roadblock... I'm performance testing and I'm working with an `TypeError: unhashable type: 'MyCustomModel'` while trying to use a custom Django model in a list comprehension. I'm attempting to filter a queryset based on some criteria and then create a list of instances of `MyCustomModel`. Here’s a simplified version of what I'm trying to do: ```python class MyCustomModel(models.Model): name = models.CharField(max_length=100) value = models.IntegerField() # Fetch some data from another model related_objects = RelatedModel.objects.filter(some_field=value) # Now, I want to create a list of MyCustomModel instances based on related_objects my_custom_instances = [MyCustomModel(name=obj.name, value=obj.value) for obj in related_objects] ``` However, when I run this code, I get the behavior mentioned above. I've double-checked that `related_objects` is indeed a QuerySet and contains valid instances. I've also verified that `name` and `value` are attributes of the objects in `related_objects`. Could this scenario stem from the way I'm using the instances of `RelatedModel` in the list comprehension? Is there a specific condition or configuration in Django that could lead to this unhashable type behavior? I’ve tried to explicitly convert the objects to dictionaries but that doesn't seem to resolve the scenario. Any guidance would be much appreciated! For reference, this is a production microservice. Thanks in advance! My development environment is CentOS. What am I doing wrong? I recently upgraded to Python latest.