contentful-labs / contentful.py

This project is unofficial and currently unsupported, the official SDK can be found here: https://github.com/contentful/contentful.py
Apache License 2.0
18 stars 6 forks source link

Entry types #6

Closed JSkally closed 9 years ago

JSkally commented 9 years ago

is there some way to distinguish between entry types like:

Entry.content_type

or

...fetch(Entry).where(content_type='Article').all()
JSkally commented 9 years ago

or fetching all entries of a certain content type

tomxor commented 9 years ago

You can fetch entries matching a specific content type like this:

client.fetch(Entry).where({'content_type': 'content-type-id-goes-here'}).all()

You can get the content type of an existing entry like this:

entry.sys['contentType']['sys']['id']

The recommended approach for this would be defining your own custom class corresponding to your model, as shown in the main README file:

class Cat(Entry):
    __content_type__ = 'cat'

    name = Field(Text)
    likes = Field(List)  
    # more fields ...

Then you can simply use:

client.fetch(Cat).all()
JSkally commented 9 years ago

Thanks,

I'm grabbing existing Entries, do you still recommend defining a custom class?

tomxor commented 9 years ago

One of the benefits when defining a custom model class is that fields are mapped as instance attributes, instead of being bundled into a normal dict. So instead of using strings (e.g. entry['my_field']), you simply call entry.my_field. Since the fields are explicitly defined inside the class declaration, other developers (who might not be aware exactly how the content type is defined) - won't have to log into the website to verify it (or investigate objects at runtime) , simply check the class declaration to see the names and the types. There are also other benefits when using custom classes with the Client, as it can infer the content type and append a where clause so you don't have to. Unless it really doesn't make sense for your use case I would say :+1:.