gpt4 book ai didi

python - Django MTM 字段 : limit_choices_to = other_ForeignKeyField_on_same_model?

转载 作者:太空狗 更新时间:2023-10-30 01:10:42 24 4
gpt4 key购买 nike

我有几个看起来像这样的 django 模型:

from django.contrib.sites.models import Site

class Photo(models.Model):
title = models.CharField(max_length=100)
site = models.ForeignKey(Site)
file = models.ImageField(upload_to=get_site_profile_path)

def __unicode__(self):
return self.title


class Gallery(models.Model):
name = models.CharField(max_length=40)
site = models.ForeignKey(Site)
photos = models.ManyToManyField(Photo, limit_choices_to = {'site':name} )

def __unicode__(self):
return self.name

我在尝试让 limit_choices_to 在 Gallery 模型上工作时遇到了各种乐趣。我只希望管理员显示与该画廊属于同一网站的照片的选择。这可能吗?

最佳答案

是的。您需要覆盖管理员用于 Gallery 模型的表单,然后限制该表单中 photos 字段的查询集:

class GalleryAdminForm(django.forms.ModelForm):

class Meta:
model = Gallery

def __init__(self, *args, **kwargs):
super(GalleryAdminForm, self).__init__(*args, **kwargs)
self.fields['segments'].queryset = Photo.objects.filter(site=self.instance.site)


class GalleryAdmin(django.contrib.admin.ModelAdmin):
form = GalleryAdminForm

django.contrib.admin.site.register(Gallery, GalleryAdmin)

关于python - Django MTM 字段 : limit_choices_to = other_ForeignKeyField_on_same_model?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/345401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com