django - 将LogEntry加入实际模型

时间:2011-12-22 18:42:55

标签: django join django-models django-templates django-queryset

所以我使用admin LogEntry对象/表来记录我的应用程序中的事件。我有一个视图,我想显示每个LogEntry 如果我可以将LogEntry与它们所代表的实际对象一起加入,那将是非常好的(所以我可以显示与日志条目内联的对象的属性) 理论上这应该很容易,因为我们从LogEntry获得了模型类型和id,但我无法弄清楚如何使用查询集来连接它们。

我以为我可以抓住不同对象的所有ID并为每种对象类型创建另一个字典然后以某种方式加入它们(也许将列表压缩在一起?)但这看起来很愚蠢而且不是非常djano-ish / pythonic。

有人有更好的建议吗?

** 修改 ** 只是想澄清我不打算使用admin,而是滚动自定义视图和模板。

2 个答案:

答案 0 :(得分:2)

据我所知,Django使用contenttypes framework在admin中执行日志记录。因此,您应该在模型中创建通用关系,然后在管理中使用GenericTabularInline和GenericStackedInline显示内联。请查阅文章。

from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.contrib.contenttypes.generic import  GenericTabularInline
from django import forms
from some_app import models
from some_app.models import Item

class LogForm(forms.ModelForm):
    class Meta:
        model = LogEntry

class LogInline(GenericTabularInline):
    ct_field = 'content_type'
    ct_fk_field = 'object_id'
    model = LogEntry
    extra = 0

class ItemForm(forms.ModelForm):
    class Meta:
        model = Item

class ItemAdmin(admin.ModelAdmin):
    form = ItemForm
    inlines = [LogInline,]


admin.site.register(models.Item, ItemAdmin)

然后添加到项目:

class Item(models.Model):
    name = models.CharField(max_length=100)
    logs =  generic.GenericRelation(LogEntry)

此更改不会在您的数据库中创建任何内容,因此无需同步

答案 1 :(得分:0)

最近的Django版本需要为LogEntry创建代理:

from django.contrib import admin
from django.contrib.admin.models import LogEntry
from django.contrib.contenttypes.generic import  GenericTabularInline

class LogEntryProxy(LogEntry):
    content_object = GenericForeignKey('content_type', 'object_id')
    class Meta:
        proxy = True

class LogInline(GenericTabularInline):
    model = LogEntry
    extra = 0

class ItemAdmin(admin.ModelAdmin):
    inlines = [LogInline,]

admin.site.register(models.Item, ItemAdmin)