3

I am trying to make search for a string through all the fielsd of one table in my models. I tried to use the "._meta.fields" django trick, but it gives me back all the fields, including the Foregn Key fields. How can I exclude these ? And get only the "local" fields from a table ?

for example I have :

class Info(models.Model):
    concerning      = models.ForeignKey(User)
    name            = models.CharField(max_length=100 , blank=True)
    value           = models.CharField(max_length=1000, blank=True)
    creation_date   = models.DateTimeField(auto_now_add=True)

And I want to get : ( name , value, creation_date)

I had a look to these pages but could not find a way:

https://code.djangoproject.com/wiki/new_meta_api

Search multiple fields of django model without 3rd party app

Get model's fields in Django

Scott Stafford
  • 43,764
  • 28
  • 129
  • 177
Romain Jouin
  • 4,448
  • 3
  • 49
  • 79

1 Answers1

4

Just check the class of the field using isinstance():

simple_field_names = [field.name for field in Info._meta.fields
                             if field.name != 'id' and
                                not isinstance(field, models.ForeignKey)]

If you want to get list of text fields only then you can pass a list of required classes to isinstance() function:

text_field_names = [field.name for field in Info._meta.fields
                    if isinstance(field, (models.CharField, models.TextField))]
catavaran
  • 44,703
  • 8
  • 98
  • 85