2013-03-01 93 views
4

我試圖解決下面的問題,經過一些搜索後,它似乎是Django中的開放bug。我通過向模型子類添加類方法來解決該問題,儘管此解決方案有效,但仍需要使用此子類對任何(模型)表單進行另一個自定義檢查。我發佈了這個爲其他人尋找解決方案比我早,其他解決方案也歡迎。強制與模型繼承的唯一

class Foo(models.Model): 
    attr1 = models.IntegerField() 
    attr2 = models.IntegerField() 

    class Meta: 
     unique_together = (
      ('attr1', 'attr2'), 
     ) 


class Bar(Foo): 
    attr3 = models.IntegerField() 

    class Meta: 
     unique_together = (
      ('attr1', 'attr3'), 
     ) 

提出:

Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.commands.runserver.Command object at 0x10f85a0d0>> 
Traceback (most recent call last): 
    File "/Users/intelliadmin/VirtualEnvs/virtenv9/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 91, in inner_run 
    self.validate(display_num_errors=True) 
    File "/Users/intelliadmin/VirtualEnvs/virtenv9/lib/python2.7/site-packages/django/core/management/base.py", line 270, in validate 
    raise CommandError("One or more models did not validate:\n%s" % error_text) 
django.core.management.base.CommandError: One or more models did not validate: 
app.Bar: "unique_together" refers to attr1. This is not in the same model as the unique_together statement. 

回答

4

一種可能的解決方案:

class Bar: 
    # fields... 

    @classmethod 
    def _validate_unique(cls, self): 
     try: 
      obj = cls._default_manager.get(attr1=self.attr1, attr3=self.attr3) 
      if not obj == self: 
       raise IntegrityError('Duplicate') 
     except cls.DoesNotExist: 
      pass 

    def clean(self): 
     self._validate_unique(self) 
     super(Bar, self).clean()