2013-10-11 56 views
18

我有以下models.pyDjango的回归和相关模型

class Contact(models.Model): 
    pass 

class Link(models.Model): 
    pass 

class Relationship(models.Model): 
    # Documentation 
    __doc__ = _(u'Stores a relationship between 2 contacts.') 
    # Attributes 
    from_contact = models.ForeignKey(Contact, related_name='from_contacts', verbose_name=_(u'first contact'), help_text=_(u'The first contact implicated by the relationship.')) 
    link = models.ForeignKey(Link, related_name=u'relationships', verbose_name=_(u'relationship link'), help_text=_(u'The relationship link between both contacts.')) 
    to_contact = models.ForeignKey(Contact, related_name='to_contacts', verbose_name=_(u'second contact'), help_text=_(u'The second contact implicated by the relationship.')) 

    # Meta-data 
    class Meta: 
     verbose_name = u'Relationship' 
     verbose_name_plural = u'Relationships' 
     unique_together = ('from_contact', 'link', 'to_contact') 

使用Django的基于类的视图和Revision Context Manager,我可以创造修订随时创建2个触点之间的新关系

# part of my views.py 
class RelationshipCreateView(LoginRequiredMixin, CreateView): 
    template_name = u'frontend/relationships/relationship-create.html' 
    model = Relationship 
    form_class = RelationshipForm 

    def get_success_url(self): 
     return reverse_lazy('contact-detail', kwargs={'contact_pk': self.kwargs['contact_pk']}) 

    def form_valid(self, form): 
     contact = Contact.objects.get(pk=self.kwargs['contact_pk']) 
     link = form.cleaned_data['link'] 
     other = form.cleaned_data['other'] 
     inverse = form.cleaned_data['inverse_relationship'] 
     relationship = None 
     if not inverse: 
      relationship = Relationship(
       from_contact=contact, 
       link=link, 
       to_contact=other 
      ) 
     else: 
      relationship = Relationship(
       from_contact=other, 
       link=link, 
       to_contact=contact 
      ) 
     with reversion.create_revision(): 
      relationship.save() 
      reversion.set_comment(_(u'A relationship has been added between %(from)s and %(to)s' % {'from': relationship.from_contact, 'to': relationship.to_contact})) 
     return HttpResponseRedirect(self.get_success_url()) 

但是只有其中一个联系人获得修订版(第一个)以及随附的评论。如何使用Revision Context Manager来创建两个修订版本?

+0

尝试循环内一个列表['从','到'],第二次是反向关系。 – jcs

+0

你说的是保存两个联系人? – TonyEight

+1

我知道这个问题很老,但你有没有解决这个问题?你[注册外键要遵循](http://django-reversion.readthedocs.org/en/latest/api.html#advanced-model-registration)? – tutuDajuju

回答

5

可能有点晚了,但我想用最新版本的回复,你可以遵循关系:

此行添加到模型的结尾:

reversion.register(Relationship, follow=['from_contact', 'link', 'to_contact'])

-1

Django Model Utils是追踪模型和模型领域的变化以及做很多其他非常酷的东西的新的最佳实践方式。

+0

如果您参考了[FieldTracker](https://django-model-utils.readthedocs.org/en/latest/utilities.html#field-tracker),那么:bravo!正是我们当时需要的! Thanx,无论如何:) – TonyEight

+0

的确是这样!方便:) – TimmyGee

+0

这不是对这个问题的回答。 – acidjunk