0

Deleting posts via Django command does not work. I do not know what to do, I am at a dead end. I hope you can help me...

delnc.py File command

class Command(BaseCommand):
    help = 'Командa для удаления всех постов из категории'
    requires_migrations_checks = True
    missing_args_message = 'Недостаточно аргументов'

    def add_arguments(self, parser):
        parser.add_argument('category_name', type=str)

    def handle(self, *args, **options):
        print('Мастер код: 7548')
        answer = input('Введите Мастер код для удаления: ')

        if answer == '7548':
            try:
                category = str(options['category_name'])
                Post.objects.filter(postCategory__category_name=category).delete()
                Post.save()
                self.stdout.write(self.style.SUCCESS(f'Успешно. Все новости категории {category} удалены!'))
            except Post.DoesNotExist:
                self.stdout.write(self.style.ERROR('Нет такой категории! Отказано!'))
        else:
            self.stdout.write(self.style.ERROR('В доступе отказано!'))

models.py

class Category(models.Model):
    category_name = models.CharField(max_length=64, unique=True)
    subscribers = models.ManyToManyField(User, blank=True, null=True)

    class Meta:
        verbose_name = 'Категория'
        verbose_name_plural = 'Категории'

    def __str__(self):
        return self.category_name

class Post(models.Model):
    PostAuthor = models.ForeignKey(Author, on_delete=models.CASCADE, verbose_name='Автор поста')

    PostNews = 'PN'
    PostArticle = 'PA'

    # «статья» или «новость»
    POSITIONS = [
        (PostArticle, 'Статья'),
        (PostNews, 'Новость'),
    ]

    postCategory = models.ManyToManyField(Category, verbose_name='Категория поста',  through='PostCategory')
    title = models.CharField(max_length=50, verbose_name='Название')
    positions = models.CharField(max_length=2, choices=POSITIONS, default=PostArticle, verbose_name='Тип поста')
    category_id = models.ForeignKey(Category, verbose_name='Категория', null=True, on_delete=models.CASCADE, related_name='category_id')
    data = models.DateTimeField(auto_now_add=True, verbose_name='Дата создания')
    data_update = models.DateTimeField(auto_now=True, verbose_name='Дата редактирования')
    photo = models.ImageField(upload_to='photos/%Y/%m/%d/', verbose_name='Фото', blank=True, default='/photos/def/1.jpg/')
    previewName = models.CharField(max_length=128, verbose_name='Превью поста')
    text = models.TextField(verbose_name='Текст поста')
    rating = models.SmallIntegerField(default=0, verbose_name='Рейтинг')
    public = models.BooleanField(default=True, verbose_name='Опубликовано')

    def like(self):
        self.rating +=1
        self.save()

    def dislike(self):
        self.rating -=1
        self.save()

    def preview(self):
        return self.text[0:124] + '...'

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Пост'
        verbose_name_plural = 'Посты'

    def get_absolute_url(self):
        return f'/news/{self.pk}'

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        cache.delete(f"new-{self.pk}")

Here is the output from the console

enter image description here

But he does not delete anything, although he writes that everything was completed successfully

2
  • 1
    the call to Post.save() does not do anything, because it is called on the model class and not on an instance. I don't think you need that call, because .delete() already does the work. Commented Jul 10, 2021 at 15:14
  • 1
    You can check the filtered objects doing multiple steps instead of one step: posts = Post.objects.filter(postCategory__category_name=category), then print(posts) and finally posts.delete(); this will show you if any objects were found Commented Jul 10, 2021 at 15:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.