1

Let us say you have a simple model with a mandatory foreign key:

class Pupil(models.Model):
    name = models.CharField(max_length=40)
    teacher = models.ForeignKey(Teacher)

I want to load Pupil instances from a fixture file but add a default teacher in my code such that the teacher must not be entered in the fixture file:

- model: models.Pupil
  pk: 1
  fields: { name: "Max" }

I tried to assign the teacher in init like this:

def __init__(self):
    super().__init__()
    self.teacher = Teacher()

and similar things also in save but without success.

Kit Fisto
  • 4,385
  • 5
  • 26
  • 43
  • 1
    you mean ``class Pupil(models.Model):`` instead of ``class Pupil:`` right? – doniyor Nov 28 '14 at 11:53
  • do it in separate *.py file (you can add it's call to fabfile) or in django shell, because data fixtures semantically cannot have logic manipulation – madzohan Nov 28 '14 at 12:23
  • @doniyor: Right, fixed, thanks. – Kit Fisto Nov 28 '14 at 12:29
  • you need to look up how to use `super` https://docs.python.org/2/library/functions.html#super maybe also how instance attributes work (hint: `self.teacher`) – Anentropic Nov 28 '14 at 12:35
  • you want all pupils to have the same teacher, or every pupil to have a different teacher? – Anentropic Nov 28 '14 at 12:36
  • @Anentropic: Each one has its own teacher. Of course pupil/teacher is not the real problem domain ;) – Kit Fisto Nov 28 '14 at 13:23
  • re `self.teacher` it was the `__init__` method that was wrong not the class definition. you need to read some basic information about Python language and think through carefully what you are doing – Anentropic Nov 28 '14 at 13:25
  • @Anentropi: Look here https://docs.python.org/3/library/functions.html#super – Kit Fisto Nov 28 '14 at 13:43

0 Answers0