brad
brad

Reputation: 501

django test model field

i'm currently writing tests for my django project and i need to make sure

that a specific field of a model is of a certain type.

for example in model Pictures i want to make sure that there is a field with the

name "image" and that he of type ImageField.

i also want to be able to check if an attribute is of type ForeignKey of

model Pictures.

i tried to use the assertIsInstance, but i need to assign the attribute or else

he is None.

does someone know how to do it?

Upvotes: 1

Views: 2582

Answers (1)

Josh Kupershmidt
Josh Kupershmidt

Reputation: 2710

To answer your question, a check like this should work:

from django.db.models import ImageField
from wherever.mymodels import Pictures
...
field = Pictures._meta.get_field("image")
assertTrue(isinstance(field, ImageField))

Though, for my 2¢, it may make more sense for your unit test to check that setting the "image" of some Picture instance works as-expected, rather than just checking for an ImageField named "image". After all, what you should really be checking with a test case is: "will the code I'm using to upload/validate/save images reliably work"?

Upvotes: 3

Related Questions