Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

django - Django_filter: How to specify the fields from a Foreign Key using Multiple choice filter?

I have a database (django model) containing DNA sequences with certain informations (not relevant here) which are associated with a Foreign Key (species name)to species informations. I want to research the sequences via the species name using django_filter MultipleChoiceFilter. the problem is: the choices which appear to the users are the species id not the species name. I tried to define a custom class to only display species name however it does not change anything. Maybe I should specify something in the init() function ? Thank you for your help. Here are my models:

class Especes(models.Model):
    nom_espece = models.CharField(max_length=100,unique=True)
    famille = models.CharField(max_length=100)
    ordre = models.CharField(max_length=100)
    classe = models.CharField(max_length=100)
    embranchement = models.CharField(max_length=100)
    regne = models.CharField(max_length=100)
    pays = models.CharField(max_length=100)

    class Meta:
        verbose_name = 'especes'

    def _str_(self):
        return self.nom_espece

class Sequences(models.Model):
    numero_sequence = models.IntegerField()
    sequences = models.CharField(max_length=1000000)
    gene = models.CharField(max_length=100)
    nombre_pdb = models.IntegerField()#check how to limit integer field ??
    amorces = models.CharField(max_length=1000)
         espece=models.ForeignKey(Especes,on_delete=models.CASCADE,related_name='liste_sequence',default=None)
    auteurs = models.CharField(max_length=100)
    annee_publication = models.IntegerField()
    groupe_recherche = models.CharField(max_length=100)
    institut = models.CharField(max_length=100)

    class Meta:
        verbose_name = 'numero_sequence'

    def _str_(self):
        return self.gene

Here is my filters.py file:

class MyMultipleChoiceFilter(django_filters.ModelChoiceFilter):
      def label_from_instance(self, obj):
         return obj.nom_espece

class SequencesFilter(django_filters.FilterSet):
     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)

espece = MyMultipleChoiceFilter(queryset=Especes.objects.all(),label='Species')

class Meta:
    model = Sequences
    fields = '__all__'
    exclude = ['espece','sequences', 'nombre_pdb', 'amorces', 'auteurs', 'annee_publication', 'groupe_recherche',
               'institut']`

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...