26👍
firstly, you must be very careful overriding __init__
to have non-optional arguments. remember it will be called every time you get an object from a queryset!
this is the correct code you want:
class Animal(models.Model):
#class Meta: #uncomment this for an abstract class
# abstract = True
aul = models.ForeignKey(Aul)
weight = models.IntegerField(default=3)
quality = models.IntegerField(default=10)
age = models.IntegerField(default=0)
def __unicode__(self):
return self.age
class Sheep(Animal):
wool = models.IntegerField()
I highly suggest setting the abstract option on Animal if you will only ever be using subclasses of this object. This ensures a table is not created for animal and only for Sheep (etc..). if abstract is not set, then an Animal table will be created and the Sheep class will be given it’s own table and an automatic ‘animal’ field which will be a foreign key to the Animal model.
10👍
Django docs recommend against you to use __init__
method in models:
You may be tempted to customize the model by overriding the
__init__
method. If you do so, however, take care not to change the calling signature as any change may prevent the model instance from being saved. Rather than overriding__init__
, try using one of these approaches:
- Add a classmethod on the model class
- Add a method on a custom manager (usually preferred)
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-How to backup a django db
- [Django]-How can modify request.data in django REST framework
0👍
While my error message was the same, my issue was not related to __init__
. This is the top related question on this topic so I’ll add my solution here as well.
My issue had something to do with trying to access a related object through a ForeignKey twice in a row. It worked fine the first time but errored out the second time even though nothing changed. So, what worked was just requerying the object before running my function a second time. So, something like:
Before:
class Animal(models.Model):
def send(self, data):
user = self.user
...
pet = Animal.objects.get(id=5)
pet.send(data)
...
pet.send(data)
After:
class Animal(models.Model):
def send(self, data):
user = self.user
...
pet = Animal.objects.get(id=5)
pet.send(data)
...
pet = Animal.objects.get(id=5)
pet.send(data)
- [Django]-In PyCharm, how to navigate to the top of the file?
- [Django]-DRF testing: instead of JSON an OrderedDict is returned
- [Django]-Django count RawQuerySet