Django foreign key starting with nothing

Ryan Saxe

So often it is important to have a ForeignKey connection that starts with nothing and then has something added

here are my models

class Class(models.Model):
    title = models.CharField(max_length=30)
    threshold = models.PositiveIntegerField(validators=[MaxValueValidator
        (100),MinValueValidator(60)])
    works = models.ForeignKey(Work,null=True) #blank=True also doesn't work

so I create a class that has no Work, which logically makes sense:

math = Class("math",90)
math.save()

now lets say we have homework and quizzes that are Work instances:

math.works.add(homework,quizzes)
#gives the following error
AttributeError: 'NoneType' object has no attribute 'add'

math.works is clearly empty to start, and that makes sense, but this will not let me add anything!

How would I be able to start a ForeignKey with nothing and then be able to add to it?

John

My two cents. First, i think you should move your foreignkey to work class not in Class class. add() is for manytomany fieldSee documentation

class work(models.Model):
.....
subject = models.ForeignKey(Class,null=True)

So that the relationship is built as your intention. homework, quizzes as instances of work class both are related to math as an instance of Class class.

when you try to save, do as following:

>>> homework = work.objects.get(pk=1)
>>> math = Class.objects.get(pk=1)
>>> homework.subject = math
>>> homework.save()
>>> quizzes = work.objects.get(pk=2)
>>> math = Class.objects.get(pk=1)
>>> quizzes.subject = math
>>> quizzes.save()

Now you can retrieve all the work for given Class:

math = Class.objects.get(pk=1)
math.work_set.all()

it will return you all the instances that are related to math, and in your case, will be homework and quizzes.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related