简体   繁体   中英

Writing a cleaner function in python, a parameter to be either a set or a value

I have a struggling with a way of writing this function much cleaner and to make this function for the parameter objs to can be either a QuerySet or an single object, in case when the objs parameter is an set of objects I want to go with the for loop but in the case when is a single object I want to create the date parameter without looping, and also I am not sure if the try block is the good way for checking if the object with these information is already in db or not and if it's not I want to create it with these dates. Any help would be appreciated, thanx!

the function:

def check_recurrent_or_new(user, objs, obj):
    for item in objs:
        if item.created_date.month == 12:
            date = datetime(
                    item.created_date.year + 1, 1, item.created_date.day,
                    item.created_date.hour, item.created_date.minute, item.created_date.second,
                    item.created_date.microsecond
                )
        else:
            date = datetime(
                    item.created_date.year, item.created_date.month + 1, item.created_date.day,
                    item.created_date.hour, item.created_date.minute, item.created_date.second,
                    item.created_date.microsecond
                )
        try:
            obj.objects.get(
                user=user, name=item.name, amount=item.amount,
                created_date=date, category=item.category, recurrent=True
            )
        except:
            obj.objects.create(
                    user=user, name=item.name, amount=item.amount,
                    created_date=date, category=item.category, recurrent=True

for the try,except you can directly use get_or_create method for more information check it here

def check_recurrent_or_new(user, objs, obj):
for item in objs:
    test=item.created_date.month == 12
    date = datetime(
                item.created_date.year + 1 if test else item.created_date.year ,1 if test else item.created_date.month + 1, item.created_date.day,
                item.created_date.hour, item.created_date.minute, item.created_date.second,
                item.created_date.microsecond
            )
    obj,created=obj.objects.get_or_create(
            user=user, name=item.name, amount=item.amount,
            created_date=date, category=item.category, recurrent=True
        )
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM