Django管理界面显示相关字段的计数

huangapple go评论76阅读模式
英文:

Django Admin display Count of related field

问题

I am building a Django project for a workshop (car/motorcycle).

Have a customer class in models and a service class. In the admin I want to display the number of services per customer, I am taught to use the get_queryset and define a variable for that count, but it doesn't want to work, probably it's like a really easy fix but I can't get my head around it! Hope someone here knows, thanks a lot! Django管理界面显示相关字段的计数

MODELS.PY

from django.db import models

# Create your models here.
class Fordonsregister(models.Model):
    regnr = models.CharField(max_length=6, primary_key=True, null=False, blank=False)
    namn = models.CharField(max_length=255, null=True, blank=True)
    tel = models.CharField(max_length=255, default='070-000 00 00', null=True, blank=True)
    email = models.EmailField(null=True, blank=True)
    kund_sedan = models.DateTimeField(auto_now=True)
    kund_points = models.IntegerField(default=0)

    def __str__(self):
        return self.regnr

    class Meta:
        ordering = ['regnr']

class ServiceTypes(models.Model):
    typ = models.CharField(max_length=255, primary_key=True, blank=False)
    pris = models.DecimalField(decimal_places=2, max_digits=6, null=False, blank=False)
    beskrivning = models.CharField(max_length=255, null=True, blank=True)

    def __str__(self):
        return self.typ

    class Meta:
        ordering = ['typ']


class FordonsService(models.Model):
    regnr = models.ForeignKey(Fordonsregister, on_delete=models.CASCADE)
    typ = models.ForeignKey(ServiceTypes, on_delete=models.CASCADE)
    service_datum = models.DateTimeField()
    bokat_datum = models.DateTimeField(auto_now=True)
    kommentar = models.CharField(max_length=1000)

    class Meta:
        ordering = ['-service_datum']

ADMIN.PY

from django.contrib import admin
from django.db.models import Count
from django.http import HttpRequest
from .models import Fordonsregister, ServiceTypes, FordonsService

# Register your models here.
@admin.register(Fordonsregister)
class FordonsregisterAdmin(admin.ModelAdmin):
    list_display = ['regnr', 'namn', 'tel', 'email', 'post_count']
    search_fields = ['regnr__istartswith']
    # list_select_related = ['fordonsservice']

    def post_count(self, obj):
        return obj.post_count

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.annotate(post_count=Count("fordonsservice"))
        return queryset


@admin.register(FordonsService)
class FordonsServiceAdmin(admin.ModelAdmin):
    list_display = ['regnr', 'typ', 'service_datum', 'bokat_datum']


@admin.register(ServiceTypes)
class ServiceTypesAdmin(admin.ModelAdmin):
    list_display = ['typ', 'pris']

The error thrown is:

FieldError at /admin/main/fordonsregister/
Cannot resolve keyword 'service_datum' into field. Choices are: email, fordonsservice, kund_points, kund_sedan, namn, regnr, standardoffert, tel

I am quite good with Python but mainly data analysis, quite new to Django Django管理界面显示相关字段的计数

英文:

I am building a Django project for a workshop (car/motorcycle).

Have a customer class in models and a service class. In the admin I want to display the number of services per customer, I am taught to use the get_queryset and define a variable for that count, but it doesn't want to work, probably its like a really easy fix but I can't get my head around it! Hope someone here knows, thanks a lot! Django管理界面显示相关字段的计数

MODELS.PY

from django.db import models

# Create your models here.
class Fordonsregister(models.Model):
    regnr = models.CharField(max_length=6, primary_key=True, null=False, blank=False)
    namn = models.CharField(max_length=255, null=True, blank=True)
    tel = models.CharField(max_length=255, default='070-000 00 00', null=True, blank=True)
    email = models.EmailField(null=True, blank=True)
    kund_sedan = models.DateTimeField(auto_now=True)
    kund_points = models.IntegerField(default=0)

    def __str__(self) -> str:
        return self.regnr

    class Meta:
        ordering = ['regnr']

class ServiceTypes(models.Model):
    typ = models.CharField(max_length=255, primary_key=True, blank=False)
    pris = models.DecimalField(decimal_places=2, max_digits=6, null=False, blank=False)
    beskrivning = models.CharField(max_length=255, null=True, blank=True)

    def __str__(self) -> str:
        return self.typ

    class Meta:
        ordering = ['typ']


class FordonsService(models.Model):
    regnr = models.ForeignKey(Fordonsregister, on_delete=models.CASCADE)
    typ = models.ForeignKey(ServiceTypes, on_delete=models.CASCADE)
    service_datum = models.DateTimeField()
    bokat_datum = models.DateTimeField(auto_now=True)
    kommentar = models.CharField(max_length=1000)

    class Meta:
        ordering = ['-service_datum']

ADMIN.PY

from django.contrib import admin
from django.db.models import Count
from django.http import HttpRequest
from .models import Fordonsregister, ServiceTypes, FordonsService

# Register your models here.
@admin.register(Fordonsregister)
class FordonsregisterAdmin(admin.ModelAdmin):
    list_display = ['regnr', 'namn', 'tel', 'email', 'post_count']
    search_fields = ['regnr__istartswith']
    # list_select_related = ['fordonsservice']

    def post_count(self, obj):
        return obj.post_count

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.annotate(post_count=Count("regnr"))
        return queryset


@admin.register(FordonsService)
class FordonsServiceAdmin(admin.ModelAdmin):
    list_display = ['regnr', 'typ', 'service_datum', 'bokat_datum']


@admin.register(ServiceTypes)
class ServiceTypesAdmin(admin.ModelAdmin):
    list_display = ['typ', 'pris']

The error thrown is:

FieldError at /admin/main/fordonsregister/
Cannot resolve keyword 'service_datum' into field. Choices are: email, fordonsservice, kund_points, kund_sedan, namn, regnr, standardoffert, tel

I am quite good with Python but mainly data analysis, quite new to Django Django管理界面显示相关字段的计数

答案1

得分: 1

我弄清楚了,我需要在表格和两个下划线前缀列名...

因此,在下面的脚本中:

Count("service_datum")
变成:
Count("fordonsservice__service_datum")

@admin.register(Fordonsregister)
class FordonsregisterAdmin(admin.ModelAdmin):
    list_display = ['regnr', 'namn', 'tel', 'email', 'post_count']
    search_fields = ['regnr__istartswith']
    # list_select_related = ['fordonsservice']

    def post_count(self, fordonregister):
        return fordonregister.post_count

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.annotate(post_count=Count("fordonsservice__service_datum"))
        return queryset
英文:

Ok I figured it out, I needed to prefix the column with the table and two underscores...

So in the script below:

Count("service_datum")
becomes:
Count("fordonsservice__service_datum")

@admin.register(Fordonsregister)
class FordonsregisterAdmin(admin.ModelAdmin):
    list_display = ['regnr', 'namn', 'tel', 'email', 'post_count']
    search_fields = ['regnr__istartswith']
    # list_select_related = ['fordonsservice']

    def post_count(self, fordonregister):
        return fordonregister.post_count

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.annotate(post_count=Count("fordonsservice__service_datum"))
        return queryset ```

</details>



huangapple
  • 本文由 发表于 2023年2月27日 02:03:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75574008.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定