I created a simple blog with DRF and vue. When trying to save my Category & Tag Models Django returns objects with a null id. However, when trying to save my post objects it works fine.
Does anyone know what I'm doing wrong here?
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True, null=False)
posts = models.ManyToManyField(Post, related_name='categories', blank=True)
def __str__(self):
return self.name
def save(self, *args, **kwargs): # new
if not self.slug:
self.slug = slugify(self.name)
After I create the model I don't expect the id, but once I save the model the ID should show. Here's the manage.py shell
I get the same thing if I put it through the following serializer.
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = [
'id', 'name', 'slug'
]
I'm getting the same data back with I call my viewset endpoint as well. How do I go about getting django to generate the id's and save the models? I've tried to do it manually as well (after recreating the test db) and the results were the same. I've also tried deleting and rebuilding the migrations from scratch.
For reference here is the post model
class Post(models.Model):
owner = models.ForeignKey(User, on_delete=models.PROTECT)
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True, null=False)
body = models.TextField()
published = models.BooleanField(default=False)
published_at = models.DateTimeField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.title
def save(self, *args, **kwargs): # new
if not self.slug:
self.slug = slugify(self.title)
return super().save(*args, **kwargs)
CodePudding user response:
You did not make a call to the super().save()
, hence saving will not trigger the logic to store the Category
object in the database. You should implement this with:
class Category(models.Model):
# …
def save(self, *args, **kwargs): # new
if not self.slug:
self.slug = slugify(self.name)
super().save(*args, **kwargs) #