如何在django admin中创建自动填充和自动递增字段

发布于 2024-09-07 07:20:45 字数 667 浏览 6 评论 0原文

[更新:将问题标题更改为更具体]

抱歉,如果我没有很好地提出问题,我不知道如何做到这一点:

class WhatEver():
    number = model.IntegerField('Just a Field', default=callablefunction)
...

Where callablefunction does这个查询:

from myproject.app.models import WhatEver

def callablefunction():
    no = WhatEver.objects.count()
    return no + 1

我想自动写入下一个数字,但我不知道该怎么做。

我收到来自 callablefunction 的错误,指出它无法导入模型,我认为必须有一种更简单的方法来执行此操作。甚至没有必要使用这个,但我不知道如何使用 pk 号来做到这一点。

我在谷歌上搜索了这一点,我发现的唯一的事情是使用 save() 方法自动递增数字......但我想在保存之前在 中显示它。 ..

你会怎么办?

[Update: Changed question title to be more specific]

Sorry if I didn't make the question very well, I can't figure how to do this:

class WhatEver():
    number = model.IntegerField('Just a Field', default=callablefunction)
...

Where callablefunction does this query:

from myproject.app.models import WhatEver

def callablefunction():
    no = WhatEver.objects.count()
    return no + 1

I want to automatically write the next number, and I don't know how to do it.

I have errors from callablefunction stating that it cannot import the model, and I think there must be an easier way to do this. There's no need even to use this, but I can't figure how to do it with the pk number.

I've googled about this and the only thing I found was to use the save() method for auto incrementing the number... but I wanted to show it in the <textfield> before saving...

What would you do?

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

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

发布评论

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

评论(4

梦归所梦 2024-09-14 07:20:45

明白了!我希望这能帮助每个在 django 中创建自动填充和自动递增字段时遇到问题的人。解决方案是:

class Cliente(models.Model):
    """This is the client data model, it holds all client information. This
       docstring has to be improved."""
    def number():
        no = Cliente.objects.count()
        if no == None:
            return 1
        else:
            return no + 1

    clientcode = models.IntegerField(_('Code'), max_length=6, unique=True, \
    default=number)

    [... here goes the rest of your model ...]

注意:

  • number 函数不接受任何参数(甚至不包括 self)
  • 它是在模型中的所有内容之前编写的
  • 这已在 django 1.2 上进行了测试。 1

此函数将自动用下一个数字填充 clientcode 字段(即,如果您有 132 个客户,则当您添加下一个客户时,该字段将填充 clientcode 数字 133 )

我知道这对于大多数实际情况来说是荒谬的,因为 PK 号也是自动递增的,但是没有办法在 django 管理中自动填充或实际使用它。

[更新:正如我在评论中所述,有一种方法可以使用主键来实现此目的,但它不会在保存之前填充字段]

Got it! I hope this will help everyone that has any problems making a auto-filled and auto-incrementing field in django. The solution is:

class Cliente(models.Model):
    """This is the client data model, it holds all client information. This
       docstring has to be improved."""
    def number():
        no = Cliente.objects.count()
        if no == None:
            return 1
        else:
            return no + 1

    clientcode = models.IntegerField(_('Code'), max_length=6, unique=True, \
    default=number)

    [... here goes the rest of your model ...]

Take in care:

  • The number function doesn't take any arguments (not even self)
  • It's written BEFORE everything in the model
  • This was tested on django 1.2.1

This function will automatically fill the clientcode field with the next number (i.e. If you have 132 clients, when you add the next one the field will be filled with clientcode number 133)

I know that this is absurd for most of the practical situations, since the PK number is also auto-incrementing, but there's no way to autofill or take a practical use for it inside the django admin.

[update: as I stated in my comment, there's a way to use the primary key for this, but it will not fill the field before saving]

原来分手还会想你 2024-09-14 07:20:45

每个 Django 模型都已经有一个自动生成的主键

id = models.AutoField(primary_key=True)

看来您正在尝试复制已经存在的行为,只需使用对象主键。

Every Django model already has an auto-generated primary key:

id = models.AutoField(primary_key=True)

It seems you are trying to duplicate an already existing behavior, just use the object primary key.

故事与诗 2024-09-14 07:20:45

我也遇到了这个问题,我的实例是 customer.number ,它与客户 Store 相关。我很想使用如下内容:

# Don't do this:

class Customer(models.Model):
    # store = ...
    number = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        if self.number == 0:
            try:
                self.number = self.store.customer_set.count() + 1
            else:
                self.number = 1
        super(Customer, self).save(*args, **kwargs)

上述可能会导致几个问题:假设有 10 个客户,我删除了 6 号客户。下一个要添加的客户将是(似乎)第 10 个客户,然后将成为第二个客户#10。 (这可能会导致 get() 查询集中出现大错误)

我最终得到的结果是这样的:

class Store(models.Model):
    customer_number = models.IntegerField(default=1)

class Customer(models.Model):
    store = models.ForeignKey(Store)
    number = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        if self.number == 0:
            self.number = self.store.customer_number
            self.store.number += 1
            self.store.save()
        super(Customer, self).save(*args, **kwargs)

PS:

您多次抛出想要在“之前”。我想您希望在保存之前填写它,以便您可以访问它。对此我想说:此方法允许您访问 store.customer_number 来查看下一个号码。

I, too, came across this problem, my instance of it was customer.number which was relative to the customers Store. I was tempted to use something like:

# Don't do this:

class Customer(models.Model):
    # store = ...
    number = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        if self.number == 0:
            try:
                self.number = self.store.customer_set.count() + 1
            else:
                self.number = 1
        super(Customer, self).save(*args, **kwargs)

The above can cause several problems: Say there were 10 Customers, and I deleted customer number 6. The next customer to be added would be (seemingly) the 10th customer, which would then become a second Customer #10. (This could cause big errors in get() querysets)

What I ended up with was something like:

class Store(models.Model):
    customer_number = models.IntegerField(default=1)

class Customer(models.Model):
    store = models.ForeignKey(Store)
    number = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        if self.number == 0:
            self.number = self.store.customer_number
            self.store.number += 1
            self.store.save()
        super(Customer, self).save(*args, **kwargs)

PS:

You threw out several times that you wanted this field filled in "before". I imagine you wanted it filled in before saving so that you can access it. To that I would say: this method allows you to access store.customer_number to see the next number to come.

同尘 2024-09-14 07:20:45

你的代码中有错误,这就是你无法导入它的原因:

from django.db import models
class WhatEver(models.Model):
    number = models.IntegerField('Just a Field', default=0)

Yuval A 关于自动增量的说法是正确的:你甚至不需要声明这样一个字段。只需使用 pkid,它们的含义是相同的,除非模型中有复合 pk:

> w = Whatever(number=10)
> w
<Whatever object>
> w.id
None
> w.save()
> w.id
1

[更新] 好吧,我还没有尝试将可调用作为默认值。我认为如果你修复了这些错误,它一定会起作用。

You have errors in code, that's why you can't import it:

from django.db import models
class WhatEver(models.Model):
    number = models.IntegerField('Just a Field', default=0)

and Yuval A is right about auto-incrementing: you don't even need to declare such a field. Just use the pk or id, they mean the same unless there's a composite pk in the model:

> w = Whatever(number=10)
> w
<Whatever object>
> w.id
None
> w.save()
> w.id
1

[update] Well, I haven't tried a callable as a default. I think if you fix these errors, it must work.

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