我怎么待干?

时间:2014-07-04 07:21:30

标签: python django django-models dry

我正在为django模型中的数据编写一些字符串表示,我的代码非常重复。什么是避开雨的最好方法?

以下是两种方法:

def get_known_citys_string(user):
    entrys = HTTPRequestData.objects.filter(user=user)
    counter = Counter()

    for entry in entrys:
        counter[entry.city] += 1

    return counter_to_string(counter)

def get_known_devices_string(user):
    entrys = HTTPRequestData.objects.filter(user=user)
    counter = Counter()

    for entry in entrys:
        counter[entry.device] += 1

    return counter_to_string(counter)

3 个答案:

答案 0 :(得分:3)

有很多方法可以解决这个问题。这是一个:

def get_known_fields_string(user, fieldSelector):
    entrys = HTTPRequestData.objects.filter(user=user)
    counter = Counter()

    for entry in entrys:
        counter[fieldSelector(entry)] += 1

    return counter_to_string(counter)

def get_known_citys_string(user):
    return get_known_fields_string(user, lambda entry: entry.city)

def get_known_devices_string(user):
    return get_known_fields_string(user, lambda entry: entry.device)

答案 1 :(得分:2)

这就是发明功能的原因......

def common(user, field):
    entrys = HTTPRequestData.objects.filter(user=user)
    counter = Counter()

    for entry in entrys:
        counter[getattr(entry, field)] += 1

    return counter_to_string(counter)

def get_known_citys_string(user):
    return common(user, "city")

def get_known_devices_string(user):
    return common(user, "device")

答案 2 :(得分:1)

另一种选择是使用functools.partial,以获得简洁的功能性风格:

from functools import partial


def getter(attrname, user):
    entrys = HTTPRequestData.objects.filter(user=user)
    counter = Counter()

    for entry in entrys:
        counter[getattr(entry, attrname)] += 1

    return counter_to_string(counter)


# Define functions as variations on getter
get_known_citys_string = partial(getter, 'city')
get_known_devices_string = partial(getter, 'device')