Python uses set () to object to re-Solutions

Background to the issue:

ORM check out the list of multiple objects, such as

list1 = list(Adgroup.objects.filter(shop_id=shop_id,adgroup_id__in=adgroup_id_list1))

list2 = list(Adgroup.objects.filter(shop_id=shop_id,adgroup_id__in=adgroup_id_list2))

list3 = list(Adgroup.objects.filter(shop_id=shop_id,adgroup_id__in=adgroup_id_list3))

list4 = list(Adgroup.objects.filter(shop_id=shop_id,adgroup_id__in=adgroup_id_list4))

demand:

Required to re-set and the intersection of the plurality of objects inside the object list.

Up on this?

Use directly

real_obj_list = list(set(list1).union(list2, list3, list4))  # 求多个list的并集

Direct error: Adgroup class object is not the hash !!!

Focus here !!!

NOTE: set to the class object weight, and wherein the method override __eq__ __hash__ methods, if not rewrite __hash__ cause Adgroup hash of the class object is not

class Adgroup(object):
    def __init__(self, title, price):
        self.title= title
        self.price= price
        
    def __eq__(self, other):
        if isinstance(other, Adgroup):
        	# title和price相同就认为对象相同
            return ((self.title== other.title) and (self.price== other.price))  
        else:
            return False
            
    def __ne__(self, other):
        return (not self.__eq__(other))
        
    def __hash__(self):
    	# title和price相同就认为对象相同
        return hash(self.title) + hash(self.price)

Then you can use the set () object to the object list will be re-it! ! !

Published 146 original articles · won praise 66 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_38923792/article/details/103605489