将前一个条目加 1

发布于 2024-09-30 04:00:08 字数 2471 浏览 3 评论 0原文

我正在尝试设置一个项目列表,当我设置项目时,它有一个项目编号(例如 10-1000)。我希望能够添加一个新项目并将其附加到项目编号中(例如,下一个项目编号为 10-1001)。我在弄清楚第一步时遇到了一些麻烦。

这是我的 models.py

class Project(models.Model):
    client = models.ForeignKey(Clients, related_name='projects')
    created_by = models.ForeignKey(User, related_name='created_by')


    #general information
    proj_name = models.CharField(max_length=255, verbose_name='Project Name')
    quote = models.CharField(max_length=10, verbose_name='Quote #', unique=True)
    desc = models.TextField(verbose_name='Description')
    starts_on = models.DateField(verbose_name='Start Date')
    completed_on = models.DateField(verbose_name='Finished On')

    def __unicode__(self):
        return u'%s' % (self.proj_name) 

    #get the current status of the projectget_value_display
    def current_status(self):
        try:
            return self.status.all().order_by('-id')[:1][0]
        except:
            return None

我的views.py 显示了添加

@login_required
def addProject(request):
    if request.method == 'POST':
        form = AddSingleProjectForm(request.POST)
        if form.is_valid():
            project = form.save(commit=False)
            project.created_by = request.user 
            today = datetime.date.today()
            project.quote = "%s-%s" % (str(today.year)[2:4], project.quote)
            project.save()
            project.status.create(
                    value = form.cleaned_data.get('status', None)
            )            
            return HttpResponseRedirect('/project/')
    else:
        form = AddSingleProjectForm()

    return render_to_response('project/addProject.html', {
    'form': form, 'user':request.user}, context_instance=RequestContext(request))

和我的 forms.py

class AddSingleProjectForm(ModelForm):
    status = forms.ChoiceField(choices=STATUS_CHOICES)
    def __init__(self, *args, **kwargs):
        super(AddSingleProjectForm, self).__init__(*args, **kwargs)
        self.fields['status'].initial = self.instance.current_status()

    class Meta:
        model = Project
        exclude = ('pre_quote', 'created_by')

    def save(self, force_insert=False, force_update=False, commit=True):
        f = super(AddSingleProjectForm, self).save(commit=False)
        if commit:
            f.save()
            print "form save method was called with commit TRUE"
        return f

任何建议将不胜感激。
谢谢大家!

I'm trying to set up a project listing where when I set up a project it has a project number (example 10-1000). I want to be able to add a new project and have it append 1 to the project number, (example, next project # will be 10-1001). I am having a bit of trouble figuring out the first step.

here is my models.py

class Project(models.Model):
    client = models.ForeignKey(Clients, related_name='projects')
    created_by = models.ForeignKey(User, related_name='created_by')


    #general information
    proj_name = models.CharField(max_length=255, verbose_name='Project Name')
    quote = models.CharField(max_length=10, verbose_name='Quote #', unique=True)
    desc = models.TextField(verbose_name='Description')
    starts_on = models.DateField(verbose_name='Start Date')
    completed_on = models.DateField(verbose_name='Finished On')

    def __unicode__(self):
        return u'%s' % (self.proj_name) 

    #get the current status of the projectget_value_display
    def current_status(self):
        try:
            return self.status.all().order_by('-id')[:1][0]
        except:
            return None

My views.py showing the add

@login_required
def addProject(request):
    if request.method == 'POST':
        form = AddSingleProjectForm(request.POST)
        if form.is_valid():
            project = form.save(commit=False)
            project.created_by = request.user 
            today = datetime.date.today()
            project.quote = "%s-%s" % (str(today.year)[2:4], project.quote)
            project.save()
            project.status.create(
                    value = form.cleaned_data.get('status', None)
            )            
            return HttpResponseRedirect('/project/')
    else:
        form = AddSingleProjectForm()

    return render_to_response('project/addProject.html', {
    'form': form, 'user':request.user}, context_instance=RequestContext(request))

and my forms.py

class AddSingleProjectForm(ModelForm):
    status = forms.ChoiceField(choices=STATUS_CHOICES)
    def __init__(self, *args, **kwargs):
        super(AddSingleProjectForm, self).__init__(*args, **kwargs)
        self.fields['status'].initial = self.instance.current_status()

    class Meta:
        model = Project
        exclude = ('pre_quote', 'created_by')

    def save(self, force_insert=False, force_update=False, commit=True):
        f = super(AddSingleProjectForm, self).save(commit=False)
        if commit:
            f.save()
            print "form save method was called with commit TRUE"
        return f

Any suggestions would be greatly appreciated.
Thanks everyone!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲鸠 2024-10-07 04:00:08

在我看来,你的“报价”是两件事:单调递增的“项目编号”和一年。因为它们就是这样,所以它们有一个规则的结构。将它们完全从表单和视图中排除,并创建两个新字段:“quote_year”和“quote_id”。

然后你的保存看起来像这样:

def save(self, *args, **kwargs):
    if not self.quote_year and not self.quote_id:
        self.quote_year = datetime.date.today().year % 100
        quote_ids = self.objects.filter(quote_year = self.quote_year).order_by('-quote_id')
        self.quote_id = 1
        if quote_ids.exists():
            self.quote_id = quote_ids[0].quote_id + 1
    super(Project, self).save(*args, **kwargs)

这基本上测试看看是否有当前年份的 quote_ids,如果没有,则初始化为 1,否则初始化为最高的 quote_id 加 1。

为了避免悲伤,渲染报价一次又一次 ID,也将其添加到您的模型中:

@property
def quote(self):
    return '%02d-%05d' % (self.quote_year, self.quote_id)

我的代码假设您希望每年的第一个项目的数字项目部分重置为零。

It looks to me that your "quote" is two things: a monotonically incrementing "project number", and a year. Since that's what they are, they have a regular structure. Exclude them from your form and view entirely, and create two new fields: "quote_year" and "quote_id."

Your save would then look something like this:

def save(self, *args, **kwargs):
    if not self.quote_year and not self.quote_id:
        self.quote_year = datetime.date.today().year % 100
        quote_ids = self.objects.filter(quote_year = self.quote_year).order_by('-quote_id')
        self.quote_id = 1
        if quote_ids.exists():
            self.quote_id = quote_ids[0].quote_id + 1
    super(Project, self).save(*args, **kwargs)

This basically tests to see if there are any quote_ids for the current year and, if not, initialize to 1, otherwise initialize to the highest quote_id plus 1.

In order to save yourself grief rendering the quote ID again and again, add this to your model as well:

@property
def quote(self):
    return '%02d-%05d' % (self.quote_year, self.quote_id)

My code assumes that you want the project part of the number to reset to zero for the first project of each year.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文