修改模型层从父类继承来的字段,直接改写报错如下:

django.core.exceptions.FieldError: Local field 'authors' in class 'SmithBook' clashes with field of similar name from base class 'Book'

出现这个错误的原因在文档中已经说明: https://docs.djangoproject.com/en/1.1/topics/db/models/#field-name-hiding-is-not-permitted

 

解决方法,通过在__init__方法中操作:

class Author(models.Model):
    name=models.CharField(max_length=20)
    
class Book(models.Model):
    title=models.CharField(max_length=100)
    num_pages=models.IntegerField()
    authors=models.ManyToManyField(Author)
    
    def __unicode__(self):
        return self.title
    
    class Meta(object):
        abstract=True
        

class SmithBook(Book):
    def __init__(self,*args,**kwargs):
        super(self,Book).__init__(*args,**kwargs)
        authors=models.ManyToManyField(Author,limit_choices_to={
                "name_endswith":"Smith"
        })

 

相关文章:

  • 2021-11-25
  • 2022-12-23
  • 2022-12-23
  • 2021-06-07
  • 2022-12-23
  • 2021-06-24
  • 2022-12-23
  • 2021-07-04
猜你喜欢
  • 2022-12-23
  • 2021-07-07
  • 2022-12-23
  • 2021-12-29
  • 2021-08-19
  • 2021-11-24
  • 2022-12-23
相关资源
相似解决方案