Django MTMField:limit_choices_to = other_ForeignKeyField_on_same_model? [英] Django MTMField: limit_choices_to = other_ForeignKeyField_on_same_model?

查看:125
本文介绍了Django MTMField:limit_choices_to = other_ForeignKeyField_on_same_model?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个django模型,如下所示:

I've got a couple 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

我是有各种各样的乐趣试图获取在Gallery模型上工作的 limit_choices_to 。我只想让管理员显示属于与此图库相同的网站的照片的选择。这是可能的吗?

I'm having all kinds of fun trying to get the limit_choices_to working on the Gallery model. I only want the Admin to show choices for photos that belong to the same site as this gallery. Is this possible?

推荐答案

我将删除网站 code>照片模型,并将 ForeignKey 添加到 Gallery 。我将从 Gallery 模型中的照片字段中删除 limit_choices_to

I would delete site field on my Photo model and add a ForeignKey to Gallery. I would remove limit_choices_to from photos fields on Gallery model.

因为你使用 ForeignKey s到网站 ,这意味着网站不共享画廊和照片。因此,上面提到的那些已经没有用了。

Because you are using ForeignKeys to Sites, that means sites don't share galleries and photos. Therefore having those 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

在图库上设置网站后,所有照片将继承此属性。该网站将以 photo_instance.gallery.site

Once you set the site on a gallery all its photos will inherit this property. And the site will be accessible 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 haven't tested it.

如果您决定画廊或照片可以出现在多个网站,事情会改变或者改变。

Things change or course, if you decide that a gallery or a photo can appear in multiple sites.

这篇关于Django MTMField:limit_choices_to = other_ForeignKeyField_on_same_model?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆