Un usuario preguntó 👇

[ad_1]

Creé un conjunto de filtros Django para filtrar datos, algunos campos se filtran con relaciones.

Cuando nunca filtro con el punto final, solo devuelve todos los datos en lugar de los datos filtrados, ¿qué podría estar mal aquí?

Este es mi filtro de punto final:

http://127.0.0.1:5000/api/v1/qb/questions/?paper=26149c3b-c3e3-416e-94c4-b7609b94182d&section=59bdfd06-02d4-4541-9478-bf495dafbee1&topic=df8c2152-389a-442f-a1ce-b56d04d39aa1&country=KE

A continuación se muestra mi muestra:

from django_filters import rest_framework as filters

class QuestionFilter(filters.FilterSet):
    

    topic = django_filters.UUIDFilter(label="topic",
                                      field_name="topic__uuid",
                                      lookup_expr="icontains")
    sub_topic = django_filters.UUIDFilter(label="sub_topic",
                                          field_name="topic__sub_topic__uuid",
                                          lookup_expr="icontains")
    paper = django_filters.UUIDFilter(label="paper",
                                      field_name="paper__uuid",
                                      lookup_expr="icontains")
    section = django_filters.UUIDFilter(label="section",
                                        field_name="section__uuid",
                                        lookup_expr="icontains")
    subject = django_filters.UUIDFilter(label="subject",
                                        field_name="paper__subject__id",
                                        lookup_expr="icontains"
                                        )
    year = django_filters.UUIDFilter(label="year",
                                     field_name="paper__year__year",
                                     lookup_expr="icontains")
    country = django_filters.CharFilter(label="country",
                                        field_name="paper__exam_body__country",
                                        lookup_expr="icontains")

    class Meta:
        model = Question
        fields = ['topic', 'section', 'paper', 'sub_topic', 'subject', 'year',
                  'country']

Así que mi vista es así:

class QuestionView(generics.ListCreateAPIView):

    """Question view."""

    queryset = Question.objects.all()
    serializer_class = serializers.QuestionSerializer
    authentication_classes = (JWTAuthentication,)
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_class = QuestionFilter

Así que los modelos adjuntos al filtro son los siguientes:

class Question(SoftDeletionModel, TimeStampedModel, models.Model):
    """Questions for a particular paper model."""
    uuid = models.UUIDField(unique=True, max_length=500,
                            default=uuid.uuid4,
                            editable=False,
                            db_index=True, blank=False, null=False)
    mentor = models.ForeignKey(User, related_name="question_mentor", null=True,
                               on_delete=models.SET_NULL)
    paper = models.ForeignKey(Paper, max_length=25, null=True,
                              blank=True, on_delete=models.CASCADE)
    question = models.TextField(
        _('Question'), null=False, blank=False)
    section = models.ForeignKey(QuestionSection,
                                related_name="section_question",
                                null=True, on_delete=models.SET_NULL)
    topic = models.ForeignKey(Course, related_name="topic_question",
                              null=True, on_delete=models.SET_NULL)
    question_number = models.IntegerField(_('Question Number'), default=0,
                                          blank=False, null=False)
    image_question = models.ImageField(_('Image question'),
                                       upload_to='image_question',
                                       null=True, max_length=900)
    answer_locked = models.BooleanField(_('Is Answer locked'), default=True)
    status = models.CharField(max_length=50, choices=QUESTION_STATUSES,
                              default=ESSAY)
    address_views = models.ManyToManyField(CustomIPAddress,
                                           related_name="question_views",
                                           default=None, blank=True)
    bookmarks = models.ManyToManyField(User, related_name="qb_bookmarks",
                                       default=None, blank=True)

    def __str__(self):
        return f'self.question'

plantilla de papel

class Paper(SoftDeletionModel, TimeStampedModel, models.Model):
    """Paper model."""
    uuid = models.UUIDField(unique=True, max_length=500,
                            default=uuid.uuid4,
                            editable=False,
                            db_index=True, blank=False, null=False)
    subject = models.ForeignKey(Subject, related_name="subject",
                                null=True, on_delete=models.SET_NULL)
    mentor = models.ForeignKey(User, related_name="paper_mentor", null=True,
                               on_delete=models.SET_NULL)
    year = models.DateField(_('Year'), blank=False, null=False)
    grade_level = models.ForeignKey(ClassGrade, related_name="grade_paper",
                                    null=True, on_delete=models.SET_NULL)
    exam_body = models.ForeignKey(ExamBody, related_name="exam_body_paper",
                                  null=True, on_delete=models.SET_NULL)
    number_of_questions = models.IntegerField(_('No of questions'),
                                              blank=False, null=False)
    number_of_sections = models.IntegerField(_('No of sections'),
                                             blank=False, null=False)
    color_code = ColorField(format="hexa", default="#33AFFF", null=True)

    class Meta:
        ordering = ['created']

    def __str__(self):
        return f'self.subject.name (self.year)'

Plantilla de sección de preguntas:

class QuestionSection(SoftDeletionModel, TimeStampedModel, models.Model):
    """Question paper sections e.g Section A, B, C etc."""
    uuid = models.UUIDField(unique=True, max_length=500,
                            default=uuid.uuid4,
                            editable=False,
                            db_index=True, blank=False, null=False)
    section = models.CharField(
        _('Question Section'), max_length=100, null=False, blank=False)

    def __str__(self):
        return f'self.section'


class Course(SoftDeletionModel, TimeStampedModel, models.Model):
    """
    Topic model responsible for all topics.
    """
    uuid = models.UUIDField(unique=True, max_length=500,
                            default=uuid.uuid4,
                            editable=False,
                            db_index=True, blank=False, null=False)
    title = models.CharField(
        _('Title'), max_length=100, null=False, blank=False)
    overview = models.CharField(
        _('Overview'), max_length=100, null=True, blank=True)
    description = models.CharField(
        _('Description'), max_length=200, null=False, blank=False
    )
    country = CountryField()
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE)

    topic_cover = models.ImageField(
        _('Topic Cover'), upload_to='courses_images',
        null=True, blank=True,  max_length=900)
    grade_level = models.ForeignKey(
        ClassGrade, max_length=25, null=True,
        blank=True, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    ranking = models.IntegerField(
        _('Ranking of a Topic'), default=0, help_text=_('Ranking of a Topic')
    )

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = "Topics"
        ordering = ['ranking']

Posible respuesta

.
[ad_2]

nota: si aun no se resuelve tu pregunta por favor dejar un comentario y pronto le daremos una posible respuesta , muchas gracias

eso es todo,espero que te funcione

¿Te ha resultado útil??

0 / 0

Deja una respuesta 0

Your email address will not be published. Required fields are marked *