django-filters returns two the same models when an instance of a model has the same value

73 views Asked by At

Here is my code;

models.py

class Home(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    def __str__(self):
        return str(self.user)

class GeneralHomeFeatures(models.Model):
    home = models.ForeignKey(
        Home, on_delete=models.CASCADE, related_name="general_home_features"
    )
    home_feature = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        return str(self.home)

serializer.py

class GeneralHomeFeaturesSerializer(serializers.ModelSerializer):
    class Meta:
        model = GeneralHomeFeatures
        exclude = ["home"]

filterset.py

class HomeFilter(filters.FilterSet):
    home_feature = filters.CharFilter(field_name="general_home_features__home_feature", lookup_expr="icontains")

    class Meta:
        model = Home
        fields = [
            "home_feature",
        ]

once I give GeneralHomeFeatures class the same value twice, once filtered, it returns the same instance twice. Example; I make a request to this url - http://localhost:8000/api/homes/?home_feature=Pool and it returns this;

[
    {
        "id": 1,
        "user": "cliffaust",
        "general_home_features": [
            {
                "id": 1,
                "home_feature": "Pool"
            },
            {
                "id": 2,
                "home_feature": "Children Play Ground"
            },
            {
                "id": 7,
                "home_feature": "Pool"
            }
        ],
     },
    {
       {
        "id": 1,
        "user": "cliffaust",
        "general_home_features": [
            {
                "id": 1,
                "home_feature": "Pool"
            },
            {
                "id": 2,
                "home_feature": "Children Play Ground"
            },
            {
                "id": 7,
                "home_feature": "Pool"
            }
        ],
     },
    {
        "id": 3,
        "user": "cliffaust",
        "general_home_features": [
            {
                "id": 4,
                "home_feature": "Pool"
            },
            {
                "id": 6,
                "home_feature": "Children Play Ground"
            }
        ],
   }
       
]

because home_feature of GeneralHomeFeatures has two the same value(pool), it seems like django-filter is returning the same instance twice(based on the serializer id). I don't know if this is a fault in my code, or its just how it works. Also, is they a better way of doing something like this?

0

There are 0 answers