2010-06-30 2 views
1
def __number(): 
    # This line returns the number of the latest created object 
    # as a "Factura" object in format "n/year" 
    last = Factura.objects.filter(f_type__exact=False).latest('number') 

    # We convert it into a string and split it to get only the first number 
    spl = str(last).split('/')[0] 

    # Convert it into integer so we can do math 
    n = int(spl) 

    # Get the current year 
    y = date.today().strftime('%y') 

    # If none return 1/year 
    if n == None: 
     return str(1) + '/' + str(y) 

    # Else we increment the number in one. 
    else: 
     n = n + 1 
     return str(n) + '/' + str(y) 

설명 : '1/year' '2/year'등의 형식으로 번호를 자동 생성합니다. 사용자가 다른 번호를 입력하면 p.e. 함수는 그 다음에 나오고 다음은 565/10이됩니다.이 비단뱀 기능을 향상시키는 방법은 없습니까?

사용자가 p. 34/10 (564/10 입력 후)이 함수는 가장 큰 숫자를 따릅니다.

나는 이것을 제대로 할 수 있습니까? 더 좋은 방법이 있습니까?


업데이트 :

def __number(): 
    current_year = date.today().strftime('%y') 
    try: 
     facturas_emmited = Factura.objects.filter(f_type__exact=False) 
     latest_object = facturas_emmited.latest('number').__str__() 
     first_number = int(latest_object.split("/")[0]) + 1 
    except Factura.DoesNotExist: 
     first_number = 1 
    return '%s/%s' % (first_number, current_year) 
+1

..... PERL! –

+1

@ 그렉 나는 나 자신을 죽이는 게 좋을거야 ... hehe. Perl은 나에게 너무 앞서있다. 아마도 미래에 나는 그것을 배우려고 노력할 것이다. –

+2

벌어지는'except' 블록을 사용하지 말고, 걱정되는 특정 오류를 잡으십시오. – Daenyth

답변

2

이것은 실제로 시작에 불과하지만 일부 주석을 자체 문서화 코드로 바꾸는 것으로 시작하겠습니다.

def __number(): 
    # "Factura" object in format "n/year" 
    latest_object = Factura.objects.filter(f_type__exact=False).latest('number') 

    # Better name can be available if you explain why the first number is important and what it means 
    # Do Factura objects not have a __repr__ or __str__ method that you must cast it? 
    first_number = int(str(latest_object).split('/')[0]) 
    current_year = date.today().strftime('%y') 
    # Use "is None" rather than "== None" 
    if first_number is None: 
     return '1/%d' % current_year 
    # No else needed because of return above 
    # Why do we add 1 to first number? Comments should explain _why_, not how 
    return '%d/%d' % (first_number + 1, current_year) 
+0

여기에 코드를 설명하는 주석이 있습니다. 실제로 함수는 아직 문서화되지 않았습니다 (저의 잘못). BTW first_number는 None 일 수 없습니다. –

+0

사용할 수있는'__str__' 메서드가 있지만 latest_object 변수가 커지고 있습니다. 그것에 대해 무엇을 할 수 있습니까? –

1

lastNone 될 수 있을까? 그렇다면 다음을 확인하는 것이 좋습니다.

또 다른 개선점은 결과 문자열을 한 곳에서만 작성한다는 것입니다.

Factura 객체가 무엇인지 모르겠지만 어떤 메소드를 호출하여 n 값을 가져올 수 없습니까? 이것은 문자열로 변환하고, 그것을 분할하고 마지막 부분을 가져 오는 것보다 낫습니다.

+0

'last'는 None이 될 수 없습니다 (어떤 객체도 발견되지 않으면 DoesNotExist 예외),하지만 try : ... except 절에서이를 감쌀 수 있습니다. 나는 그 질문에 코드를 넣을 것이다. 또한'number'는 문자열이므로'n'을 직접 얻을 수있는 방법이 없습니다. –

0

object.id/year (object/id는 데이터베이스 ID 임)를 사용하여 비슷한 문제가 해결되었습니다.

이것은 고유하고 자동 증가합니다 (n = n + 1을 수행 할 필요가 없으므로 이론적으로 db에 값이 중복 될 수 있음).

save 메서드를 재정 의하여이 작업을 수행 할 수 있으며 개체를 저장하고 (ID 할당 됨) 먼저 ID/연도 번호를 만들고 다시 저장해야합니다 (두 배로하는 것이 더 좋은 방법 일 수 있습니다) 구하다).

def save(self, force_insert = False, force_update = False): 
    super(Factura, self).save(force_insert, force_update) 
    current_year = date.today().strftime('%y') 
    self.identifier = '%s/%s'%(self.id, current_year) 
    super(Factura, self).save(force_insert, force_update) 
+0

그래,하지만 내 경우에는 그 방법에는 2 가지 문제가있다. a) f_type = False 인 경우에만 쓰는 대신 모든 Factura 오브젝트에 number/year를 생성한다. b) 필드에 내 함수가 호출됩니다.default() 그래서 객체를 추가하자마자 그 필드는 자동 완성됩니다. 어쨌든 답변을 주셔서 감사합니다 :) –

+0

난 그냥 다른 접근 방식을 보여주고 싶었어요. 당신은 쉽게 당신의 필요를 위해 이것을 수정할 수 있습니다 데프 저장 (자동, force_insert = 거짓, force_update = 거짓) : 슈퍼 (Factura, 자기) .save (force_insert, force_update) self.f_type 경우 : CURRENT_YEAR = 날짜입니다. 오늘(). strftime ('% y') self.identifier = '% s/% s'% (self.id, current_year) 슈퍼 (Factura, 셀프) .save (force_insert, force_update) – dzida

+0

첫 번째 개체는 342/10이 될 수 있으므로 1 또는 다른 숫자로 시작하여 발전기가 따라야합니다. PK를 사용하는 경우 PK 순서 만 따라갈 수 있습니다 (342/10은 1/10이됩니다) –

관련 문제