Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 492
Romain Jouin Avatar asked Apr 27 '26 10:04

Romain Jouin


1 Answers

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))]
like image 94
catavaran Avatar answered Apr 30 '26 05:04

catavaran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!