只显示相关对象在Django管理界面中的方法

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

How to only show related objects in Django Admin screens

问题

我有一个应用程序,我希望管理员能够通过管理视图创建事件。我有会员,他们会有多辆车参加多次会议。我想记录他们在会议上使用的车辆。

在Django管理员视图中,对于会员,我可以成功管理他们的车辆,只有属于该会员的车辆会显示在“内联”中在会员管理员页面上显示,但尝试管理会议时,会列出所有车辆,而不仅仅是属于该会员的车辆。

我希望在MeetInline中出现与CarInline相同的车辆列表-即属于会员的注册车辆。有没有办法实现这一点?

models.py

class Member(models.model):
    member_number = models.CharField(primary_key=True, max_length=30)
    is_active = models.BooleanField(default=True)

class Car(models.model):
    member = models.ForeignKey(Member)
    registration = models.CharField(max_length=80)

class Meet(models.model):
    meet_date = models.DateTimeField()
    member = models.ForeignKey(Member)
    car = models.ManyToManyField(Car)

admin.py

class CarInline(admin.TabularInline):
    model = Car
    extra = 0
    fields = ["registration"]

class MeetInline(admin.TabularInline):
    model = Meet
    extra = 0
    fields = ["meet_date", "car"]

class MemberAdmin(admin.ModelAdmin):
    list_filter = [
        "is_active"
    ]
    search_fields = ["member_number"]
    fieldsets = [
        (None, {"fields": ["member_number", "is_active"]}),
    ]
    inlines = [CarInline, MeetInline]
英文:

I have an app where I want administrators to be able to create events via the admin view. I have members, who will have multiple cars and attend multiple meets. I want to record which vehicle they used at a meet.

In the django admin view for a member, I can manage their cars successfully and only cars belonging to that member show up in the inline on the Member Admin page, but when attempting to manage meets, all cars are listed, not only cars belonging to that member.

I want the same list of cars from the CarInline to appear in the MeetInline - i.e. cars registered to the member. Any ideas how to achieve this?

I think that the issue is that the Meet model has a ManyToMany relationship with the Car model but wasn't sure how else to model this.

models.py

class Member(models.model):
	member_number = models.CharField(primary_key=True, max_length=30)
	is_active = models.BooleanField(default=True)

class Car(models.model) 
	member = models.ForeignKey(Member)
	registration = models.CharField(max_length=80)


class Meet(models.model)
	meet_date = models.DateTimeField()
	member = models.ForeignKey(Member)
	car = models.ManyToManyField(Car)

admin.py

class CarInline(admin.TabularInline):
    model = Car
    extra = 0
    fields = ["registration"]

class MeetInline(admin.TabularInline):
    model = Meet
    extra = 0
    fields =["meet_date", "car"]

class MemberAdmin(admin.ModelAdmin):
    list_filter = [
        "is_active"
    ]
    search_fields = ["member_number"]
    fieldsets = [
        (None, {"fields": ["member_number", "is_active"]}),
    ]
    inlines = [CarInline, MeetInline]

答案1

得分: 1

Here is the translated code:

from django import forms
from django.contrib import admin

from .models import Member, Car, Meet

class CarInline(admin.TabularInline):
    model = Car
    extra = 0
    fields = ["registration"]

class MeetInline(admin.TabularInline):
    model = Meet
    extra = 0
    fields = ["meet_date", "car"]

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        """
        Override the default formfield for the 'car' field to only show cars
        belonging to the current member.
        """
        formfield = super().formfield_for_manytomany(db_field, request, **kwargs)

        if db_field.name == "car":
            member_pk = request.resolver_match.kwargs.get("object_id")
            if member_pk:
                member = Member.objects.get(pk=member_pk)
                formfield.queryset = member.car_set.all()

        return formfield

class MemberAdmin(admin.ModelAdmin):
    list_filter = ["is_active"]
    search_fields = ["member_number"]
    fieldsets = [(None, {"fields": ["member_number", "is_active"]}),]
    inlines = [CarInline, MeetInline]

admin.site.register(Member, MemberAdmin)

I've removed the HTML escape codes and provided the code in plain text format.

英文:
from django import forms
from django.contrib import admin

from .models import Member, Car, Meet


class CarInline(admin.TabularInline):
    model = Car
    extra = 0
    fields = ["registration"]


class MeetInline(admin.TabularInline):
    model = Meet
    extra = 0
    fields = ["meet_date", "car"]

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        """
        Override the default formfield for the 'car' field to only show cars
        belonging to the current member.
        """
        formfield = super().formfield_for_manytomany(db_field, request, **kwargs)

        if db_field.name == "car":
            member_pk = request.resolver_match.kwargs.get("object_id") // here i have used object_id as pk please change it according to what your pk name is
            if member_pk:
                member = Member.objects.get(pk=member_pk)
                formfield.queryset = member.car_set.all()

        return formfield


class MemberAdmin(admin.ModelAdmin):
    list_filter = ["is_active"]
    search_fields = ["member_number"]
    fieldsets = [(None, {"fields": ["member_number", "is_active"]}),]
    inlines = [CarInline, MeetInline]


admin.site.register(Member, MemberAdmin)

huangapple
  • 本文由 发表于 2023年4月19日 17:15:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052758.html
匿名

发表评论

匿名网友

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

确定