Romain Jouin
Romain Jouin

Reputation: 4838

Django get_fields but not foreignkey fields

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

Upvotes: 3

Views: 1762

Answers (1)

catavaran
catavaran

Reputation: 45575

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))]

Upvotes: 4

Related Questions