django manytomany没有被orm妥善保存

时间:2014-04-02 12:54:45

标签: python django django-models django-orm

我有两个模型由多种关系联系在一起:

class News(models.Model):
    title = models.CharField(max_length=255, blank=True, db_index=True)
    slug = models.SlugField(unique=True, db_index=True, blank=True,)

class FrontPage(models.Model):
    news = models.ManyToManyField('news.News', related_name='front_page')
    department = models.ForeignKey('department.Department', related_name='front_news', null=True,)
    picture = models.ImageField(upload_to='img/front',)

当我保存FrontPage实例时,news.all()在django shell和admin中都是空的。但是在dbshel​​l中,我可以看到关系已经正确保存了!

cms_m=> select * from news_frontpage_news where frontpage_id=12;
 id | frontpage_id | news_id 
----+--------------+---------
  7 |           12 |       6
(1 row)

任何人都可以帮我解决这个问题吗?更多详情:

class FrontPageForm(forms.ModelForm):
    class Meta:
        model = FrontPage

    news = forms.ModelMultipleChoiceField(
        queryset=News.objects.none(),
        widget=FilteredSelectMultiple(
            verbose_name=_('published news articles'),
            is_stacked=False,
        )
    )

    def __init__(self, *args, **kwargs):
        super(FrontPageForm, self).__init__(*args, **kwargs)
        self.fields['news'].queryset = News.objects.filter(is_published=True, pub_date__lte=now())

    def clean_news(self):
        data = self.cleaned_data['news']
        if data.count() != 1:
            raise forms.ValidationError(_('Please, just select one article.'))
        return data

class FrontPageAdmin(ModelAdmin):
    form = FrontPageForm

admin.site.register(FrontPage, FrontPageAdmin)

提前感谢您的任何建议!

更新:django-cms插件中的示例:

def render(self, context, instance, placeholder):
    context['news'] = FrontPage.objects.filter(
        department__exact=instance.department
    )[:3]  # these are actually 3 items
    return context

这3个FrontPage实例中只有一个在模板中有任何新闻。但在数据库中并非如此:

cms_m=> select * from news_frontpage_news;
 id | frontpage_id | news_id 
----+--------------+---------
  2 |           10 |       4
  3 |           11 |       1
  7 |           12 |       6

更新

我终于放弃了,并再次思考了整个想法。我有一个新的模型设计,它似乎工作。感谢您的所有建议!

0 个答案:

没有答案