I want to check my Foo instance if it belongs to a category yet my category is a many to many attribute thus I get "'Foo' instance needs to have a primary key value before a many-to-many relationship can be used." once I try such:
class Category(models.Model):
name = models.CharField(max_length=120)
class Movie (models.Model):
poster = models.ImageField(blank=True)
categories = models.ManyToManyField(Category)
def clean(self):
try:
self.categories.all().get(db_name="special")
self.poster.url = u'/media/special_img.png'
except Category.DoesNotExist:
pass
You can’t check if
Foobelongs to a category yet until you save it. But since it isn’t saved anyway, you can be sure that it doesn’t belong to a category yet.One way to check wheter it has been saved already is by using
if foo.pk. Thepkis the primary key and it will beNoneif it hasn’t been saved yet.