Search code examples
pythondjango-modelsdjango-rest-frameworkdjango-filters

More than one ForeignKey from same Model


I have a model Analytics

class StoreAnatytics(models.Model):
    store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True)
    tax_sum = models.DecimalField(
        max_digits=10, decimal_places=2, default=0, verbose_name="tax sum"
    )

which has a ForeignKey to model Store:

class Store(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    name = models.CharField(max_length=128, blank=True, default="", verbose_name="store name")
    type = models.PositiveSmallIntegerField(choices=MARKET, default=Amazon, verbose_name="store type")

Now I need to add a filters to my Analytics. The problem is that I have to filter by 2 fields: store (store pk) and type (store's type). I tried to add to my Analytics model a second ForeignKey field (type) from Store model. But I get:

ERRORS:
<class 'stores.admin.StoreAnalytics'>: (admin.E202) 'dashboard.StoreAnatytics' has more than one ForeignKey to 'stores.Store'. You must specify a 'fk_name' attribute.
dashboard.StoreAnatytics.type: (fields.E302) Reverse accessor for 'dashboard.StoreAnatytics.type' clashes with field name 'stores.Store.type'.
HINT: Rename field 'stores.Store.type', or add/change a related_name argument to the definition for field 'dashboard.StoreAnatytics.type'.
dashboard.StoreAnatytics.type: (fields.E303) Reverse query name for 'dashboard.StoreAnatytics.type' clashes with field name 'stores.Store.type'.

my filters.py looks like:

from dashboard.models import StoreAnatytics
from django_filters import rest_framework as filters


class StoreAnatyticsFilter(filters.FilterSet):
    store = filters.CharFilter(lookup_expr="exact")

    class Meta:
        model = StoreAnatytics
        fields = ["store"]

But I need a field "type" in it. How can I solve this task?


Solution

  • class StoreAnatyticsFilter(filters.FilterSet):
        store_id = filters.NumberFilter(field_name='store__id', lookup_expr="exact")
        store_type= add same as for type beacuse i dont know choices are integer or string
        class Meta:
            model = StoreAnatytics
            fields = ["store_id", "store_type"]