Django管理员 - 更改模型页面 - 带有UUID而不是ID的URL

发布于 2025-02-11 10:58:00 字数 520 浏览 2 评论 0原文

我有一个basemodel类,我所有的模型都以uuid喜欢这样的类似:

class BaseModel(models.Model):

    ''' Extension of base model class '''
    
    uuid = models.UUIDField(unique=True, default=uuid4, editable=False)
    ...

我如何更改django admin行为,以便我可以使用实例访问更改页面对象uuid而不是ID?

目前: .../admin/my_app/my_model/7/change/code>

首选: .../admin/my_app/my_model/b6a98f1d-6b26-4399-8d68-62ec1ce12c41/change/change/

I have a BaseModel class that all my models inherit with a uuid like so:

class BaseModel(models.Model):

    ''' Extension of base model class '''
    
    uuid = models.UUIDField(unique=True, default=uuid4, editable=False)
    ...

How can I change the django admin behavior such that I can access the change page for an instance using the object UUID instead of the ID?

Presently:
.../admin/my_app/my_model/7/change/

Preferred:
.../admin/my_app/my_model/b6a98f1d-6b26-4399-8d68-62ec1ce12c41/change/

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

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

发布评论

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

评论(1

孤单情人 2025-02-18 10:58:00

我已经管理了此解决方案,而无需将uuid设置为主要密钥:

from django.contrib import admin


class BaseModelAdmin(admin.ModelAdmin):

    """ base model admin with custom behavior """

    def get_object(self, request, object_id, from_field=None):
        """ get object based on uuid insead of id """

        # get queryset, model, field:
        queryset = self.get_queryset(request)
        model = queryset.model
        field = model._meta.get_field('uuid') if from_field is None else model._meta.get_field(from_field)
        
        # try to return instance:
        try:
            object_id = field.to_python(object_id)
            return queryset.get(**{field.name: object_id})
        except:
            return None

I've managed this solution without having to set the UUID as the primary key:

from django.contrib import admin


class BaseModelAdmin(admin.ModelAdmin):

    """ base model admin with custom behavior """

    def get_object(self, request, object_id, from_field=None):
        """ get object based on uuid insead of id """

        # get queryset, model, field:
        queryset = self.get_queryset(request)
        model = queryset.model
        field = model._meta.get_field('uuid') if from_field is None else model._meta.get_field(from_field)
        
        # try to return instance:
        try:
            object_id = field.to_python(object_id)
            return queryset.get(**{field.name: object_id})
        except:
            return None
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文