Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model?

I have a couple of django models that look like this:

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 

I have all kinds of entertainments that try to make limit_choices_to work with the Gallery model. I just want the administrator to show options for photos belonging to the same site as this gallery. Is it possible?

+5
python django foreign-keys manytomanyfield
source share
3 answers

I would remove the site field in my Photo model and add ForeignKey to Gallery . I would remove limit_choices_to from the photos fields in Gallery .

Since you are using ForeignKey to site s, this means that sites do not exchange galleries and photos. Therefore, the presence of those that I mentioned above is already useless.

 class Photo(models.Model): title = models.CharField(max_length=100) gallery = models.ForeignKey(Gallery, related_name='photos') 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) def __unicode__(self): return self.name 

Once you set a site in the gallery, all of its photos inherit this property. And the site will be available as photo_instance.gallery.site :

 @property def site(self): return self.gallery.site 

This should work as if you had a site field. But I did not test it.

Changes or course if you decide that a gallery or photo can appear on several sites.

+1
source share

Yes. You need to redefine the form that the administrator uses for the Gallery model, and then limit the set of requests in the photos field in this form:

 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) 
+3
source share

According to docs , limit_choices_to does not work when used on ManyToManyField with a staging table. "In my reading, this means that it has no effect, because ManyToManyFields use staging tables ...

I did not try to make it work on the Admin site, but from your own views you can create a form and override the set of queries used to fill out the list of options:

 form.fields["photos"].queryset = request.user.photo_set.all() 
0
source share

All Articles