Python - Django - MySQL #необходимо добавить distinct() после select_related().distinct() в views.py

Итак, это ads/views.py Есть еще ads/models.py, ads/forms, ads/urls.py и другие файлы, но тот, на который жалуется грейдер, это views.py...

3806 символов HTML получены Тест завершен: Найдена строка меню в верхней части страницы Найдено более одного объявления при поиске 'HHGTTTG_42 1717639962'. Вероятно, вам нужно добавить distinct() после select_related().distinct() ... в вашем views.py

поэтому я попробовал использовать select_related().distinct() и добавить его после, но это не работает :(

)

views.py Секция, вызывающая проблемы:

class AdListView(ListView):
    model = Ad  # Specify the model you're working with
    template_name = "ads/ad_list.html"

    def get(self, request):
        strval = request.GET.get("search", False)
        if strval:
            query = Q(title__icontains=strval) | Q(text__icontains=strval) | Q(tags__name__in=[strval])
            #query.add(Q(text__icontains=strval), Q.OR)
            #query.add(Q(tags__name__in=[strval]), Q.OR)

            ad_list = Ad.objects.filter(query).order_by('-updated_at').distinct()
        else:
            ad_list = Ad.objects.all().order_by('-updated_at')

        # Apply distinct() explicitly
        # ad_list = ad_list.distinct()

        for obj in ad_list:
            obj.natural_updated = naturaltime(obj.updated_at)

        if request.user.is_authenticated:
            favorites = list(request.user.favorite_ads.values_list('id', flat=True))
        else:
            favorites = []

        ctx = {'ad_list': ad_list, 'favorites': favorites, 'search': strval}
        return render(request, self.template_name, ctx)

models.py

    from django.db import models
from django.conf import settings
from django.core.validators import MinLengthValidator
from taggit.managers import TaggableManager

class Ad(models.Model):
    title = models.CharField(
        max_length=200,
        validators=[MinLengthValidator(2, "Title must be greater than 2 characters")]
    )
    price = models.DecimalField(max_digits=7, decimal_places=2, null=True)
    text = models.TextField()
    tags = TaggableManager(blank=True)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tagme_owner')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    picture = models.BinaryField(null=True, blank=True, editable=True)
    content_type = models.CharField(max_length=256, null=True, blank=True, help_text='The MIMEType of the file')
    comments = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Comment', related_name='tagme_comments')
    favorites = models.ManyToManyField(settings.AUTH_USER_MODEL, through='Fav', related_name='favorite_ads')

    def __str__(self):
        return self.title

class Comment(models.Model):
    text = models.TextField(
        validators=[MinLengthValidator(3, "Comment must be greater than 3 characters")]
    )
    ad = models.ForeignKey(Ad, on_delete=models.CASCADE)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.text[:20] + ("..." if len(self.text) > 20 else "")

class Fav(models.Model):
    ad = models.ForeignKey(Ad, on_delete=models.CASCADE)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

    def __str__(self):
        return self.user.username + " likes " + self.ad.title

forms.py

    from django import forms
from ads.models import Ad, Comment
from django.core.files.uploadedfile import InMemoryUploadedFile
from ads.humanize import naturalsize
from taggit.forms import TagWidget

class CreateForm(forms.ModelForm):
    max_upload_limit = 2 * 1024 * 1024
    max_upload_limit_text = naturalsize(max_upload_limit)

    picture = forms.FileField(required=False, label='File to Upload <= '+max_upload_limit_text)
    upload_field_name = 'picture'

    class Meta:
        model = Ad
        fields = ['title', 'price', 'text', 'tags', 'picture']
        widgets = {
            'tags': TagWidget(),
        }

    def clean(self):
        cleaned_data = super().clean()
        pic = cleaned_data.get('picture')
        if pic and isinstance(pic, InMemoryUploadedFile):
            if pic.size > self.max_upload_limit:
                self.add_error('picture', "File must be < " + self.max_upload_limit_text + " bytes")
        return cleaned_data

    def save(self, commit=True):
        instance = super(CreateForm, self).save(commit=False)
        f = instance.picture
        if isinstance(f, InMemoryUploadedFile):
            bytearr = f.read()
            instance.content_type = f.content_type
            instance.picture = bytearr
        if commit:
            instance.save()
            self.save_m2m()  # Save many-to-many fields like tags
        return instance

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['text']
Вернуться на верх