Twitter (X) API in Django: Models, Polling and Caching in 2026

By TwitterAPI.io Team•10 min read
Diagram of a Django X API integration: cron, services.py, a Tweet model with a unique id, cached views
Fetch on a schedule, store once, serve from cache. Collected in 2026.
TL;DR
  • Architecture: services.py (HTTP) + a management command (writes) + views that read the database only. Never call the API inside a view.
  • Dedupe in the database: tweet_id = CharField(max_length=20, unique=True) plus bulk_create(ignore_conflicts=True). In our run the second poll offered 135 posts and stored 0.
  • Model sizing from real data: text median 208 characters, max 674, 22.4% over 280, so TextField. Ids are 19 digits; store them as strings.
  • Organization accounts post slowly: the median account in our sample posted 0.65 times a day. Poll every 15 to 60 minutes, not every few seconds.
  • Cost: a timeline call returns up to 20 posts at 15 credits each, so up to $0.003 per call, up to $8.64 a month per account at 15-minute polling. A since_time: search that finds nothing costs the $0.00015 minimum.
  • Cache the view: @cache_page(60) took our 200-row feed page from a median 4.27 ms and 1 query to 0.08 ms and 0 queries on a cache hit (local machine).

This page is about wiring X (Twitter) data into a Django project: where the API call lives, what the model looks like, how the polling job is scheduled, and how the result is cached and rendered in a template. If you want plain Python scripts without a web framework, the complete Python guide to the Twitter API covers that; if you want a quick dashboard rather than a full web app, see Twitter API with Streamlit.

Everything below was run for real. We built a minimal Django project (one app, xfeed), pulled the latest timelines of eight organization accounts with /twitter/user/last_tweets, fed them through the project's management command twice, and measured what the database kept, what it skipped, which fields came back empty and what caching changed. The numbers in this page come from that run.

Repeats skipped by the unique tweet_id on the second poll

135 of 135

01 — Section

The shape of a Django + X API integration

Django apps that show tweets tend to fail in the same way: the view calls the API on every page load. That makes your page as slow as the slowest API answer, it multiplies cost by your traffic, and it breaks the page whenever the network does. The fix is to split the work into three parts that never wait on each other.

A service module. xfeed/services.py owns the HTTP call, the API key and the parsing of the response into model fields. Nothing else in the project imports requests.

A writer on a schedule. A management command (python manage.py poll_x <accounts>) calls the service and writes rows. Cron, a systemd timer or Celery beat runs it every N minutes. Django's docs describe the layout: a management/commands/ package inside an app listed in INSTALLED_APPS, a class named Command that extends BaseCommand and implements handle().

Readers. Views, templates, the admin and DRF serializers read the Tweet table. They are fast and they keep working when the API is unreachable.

This is the same split the PostgreSQL storage guide uses for raw SQL; Django just gives each part a standard home.

02 — Section

Step 1: settings and the API key

Read the key from the environment, never from a committed settings file. Requests to https://api.twitterapi.io carry it in the X-API-Key header; read endpoints need no X account and no OAuth flow.

Pick a supported Django release. The download page at djangoproject.com/download/ lists 6.1 as the latest release (6.1.4 when we checked), 6.0 with extended support until April 2027, and 5.2 LTS with extended support until April 2028. Per the install FAQ, 6.0 and 6.1 need Python 3.12 or newer, while 5.2 runs on Python 3.10 to 3.14. Our run used Django 6.1.4 on Python 3.12.13; the code below uses nothing that 5.2 lacks.

For the cache, Django's docs say the local-memory backend is the default when none is configured and that it is per process, which makes it fine for development and a poor fit for production with several workers. Django ships a Redis backend (django.core.cache.backends.redis.RedisCache); the Redis guide covers running it next to an X data pipeline.

python
# mysite/settings.py (additions)
import os

INSTALLED_APPS += ["xfeed"]
TWITTERAPI_IO_KEY = os.environ["TWITTERAPI_IO_KEY"]  # never commit the key

CACHES = {
    "default": {
        # LocMemCache is per process; use the built-in Redis backend in production
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379",
    }
}

# crontab: every 15 minutes
# */15 * * * * cd /srv/mysite && .venv/bin/python manage.py poll_x djangoproject ThePSF >> /var/log/poll_x.log 2>&1
03 — Section

Step 2: a Tweet model sized from real data

We sized the model from what the API actually returned. Across 393 unique posts the text was a median 208 characters long, the 95th percentile 324 and the longest 674; 88 posts (22.4%) were longer than 280. A CharField(max_length=280) would reject those on PostgreSQL, so text is a TextField.

Tweet ids were 19 digits. They fit a signed 64-bit BigIntegerField, but the API returns them as strings and JavaScript clients lose precision above 2^53, so a CharField(max_length=20, unique=True) is the safer key. Keep Django's own auto id as the primary key; bulk_create handles that cleanly.

The chart shows how often each field came back empty. Anything that is usually empty must be null=True, blank=True or derived from the raw JSON on demand. Our sample excluded replies (the default for last_tweets), which is why inReplyToId was always empty; if you pass includeReplies=true it will be filled for the replies.

FieldEmpty in our sampleDjango field
text0% (median 208 chars, max 674)TextField()
inReplyToId100.0% (replies excluded)CharField(null=True)
quoted_tweet98.7%keep in raw
retweeted_tweet85.2%keep in raw
extendedEntities.media71.2%keep in raw or a child model
viewCount0.0%PositiveBigIntegerField(null=True)

Storing the full API object in a JSONField costs space: the median post was 5,014 bytes of JSON and the largest 19,337. Our SQLite file held 393 rows in 3.0 MB, about 7.7 KB a row. That is cheap insurance: when you later want card titles or media URLs you read them from raw instead of refetching.

python
# xfeed/models.py
from django.db import models


class Tweet(models.Model):
    tweet_id = models.CharField(max_length=20, unique=True)  # X ids are 19 digits today
    author_username = models.CharField(max_length=15, db_index=True)
    text = models.TextField()  # not CharField(280): long posts exist
    created_at = models.DateTimeField(db_index=True)
    lang = models.CharField(max_length=8, blank=True)
    url = models.URLField(max_length=200)
    like_count = models.PositiveIntegerField(default=0)
    retweet_count = models.PositiveIntegerField(default=0)
    reply_count = models.PositiveIntegerField(default=0)
    view_count = models.PositiveBigIntegerField(null=True, blank=True)
    in_reply_to_id = models.CharField(max_length=20, null=True, blank=True)
    raw = models.JSONField()  # the full API object, for fields you add later
    fetched_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]
Bar chart of the share of posts where each tweet field was empty: place and inReplyToId 100%, quoted_tweet 98.7%, retweeted_tweet 85.2%, media 71.2%
393 unique posts from 8 organization timelines, collected in 2026.
04 — Section

Step 3: the service module

Two functions cover a typical app. fetch_last_tweets reads one account's timeline, newest first, up to 20 posts a page, following has_next_page and next_cursor; the tweets sit under data.tweets. search_since asks /twitter/tweet/advanced_search for several accounts at once with from:a OR from:b since_time:<unix>; there the tweets are at the top level under tweets. Getting that difference wrong is a common source of empty pages.

Parse createdAt with the format %a %b %d %H:%M:%S %z %Y. The value carries +0000, so the result is timezone-aware, which is what Django wants with USE_TZ = True.

An unknown or suspended account does not raise an HTTP error on the user endpoints: the body comes back with status: "error" and the reason in msg. Check it before you parse, as the single-file example at the end does.

python
# xfeed/services.py
from datetime import datetime

import requests
from django.conf import settings

BASE = "https://api.twitterapi.io"
X_DATE = "%a %b %d %H:%M:%S %z %Y"  # "Thu Oct 16 12:34:56 +0000 2026"
session = requests.Session()


def fetch_last_tweets(username, cursor=""):
    resp = session.get(
        f"{BASE}/twitter/user/last_tweets",
        headers={"X-API-Key": settings.TWITTERAPI_IO_KEY},
        params={"userName": username, "cursor": cursor},
        timeout=30,
    )
    resp.raise_for_status()
    body = resp.json()
    data = body.get("data") or {}
    return data.get("tweets") or [], body.get("has_next_page", False), body.get("next_cursor", "")


def search_since(usernames, since_unix, cursor=""):
    query = " OR ".join(f"from:{u}" for u in usernames) + f" since_time:{since_unix}"
    resp = session.get(
        f"{BASE}/twitter/tweet/advanced_search",
        headers={"X-API-Key": settings.TWITTERAPI_IO_KEY},
        params={"query": query, "queryType": "Latest", "cursor": cursor},
        timeout=30,
    )
    resp.raise_for_status()
    body = resp.json()
    return body.get("tweets") or [], body.get("has_next_page", False), body.get("next_cursor", "")


def to_model_kwargs(t):
    return dict(
        tweet_id=t["id"],
        author_username=(t.get("author") or {}).get("userName", ""),
        text=t.get("text") or "",
        created_at=datetime.strptime(t["createdAt"], X_DATE),
        lang=t.get("lang") or "",
        url=t.get("url") or "",
        like_count=t.get("likeCount") or 0,
        retweet_count=t.get("retweetCount") or 0,
        reply_count=t.get("replyCount") or 0,
        view_count=t.get("viewCount"),
        in_reply_to_id=t.get("inReplyToId"),
        raw=t,
    )
05 — Section

Step 4: the management command and what the unique constraint did

The command fetches, builds unsaved Tweet objects and hands them to bulk_create(..., ignore_conflicts=True). Django's docs say this makes the database ignore rows that fail constraints such as duplicate unique values, on every backend except Oracle. Two caveats from the same docs matter here: save() is not called and pre_save / post_save signals are not sent, and with ignore_conflicts the primary key is not set on the returned objects. If you need signals, loop with get_or_create instead and accept one query per post.

On MySQL and MariaDB the docs add a warning: ignore_conflicts=True turns some other errors, such as invalid values, into warnings. Validate first there (see the MySQL guide).

Here is what the run stored. The backfill pulled three pages per account; the second poll pulled one page per account a few minutes later.

PassPosts offeredStoredSkipped by unique id
Backfill (3 pages per account)3963933
Second poll (2.5 min later)1350135 (100.0%)

The 3 repeats inside the backfill were the same post returned on more than one page of a timeline, for three accounts. Code that counts len(tweets) as new rows would have overcounted; the database did not. The second poll found nothing new for any account, which leads straight to the cost question.

python
# xfeed/management/commands/poll_x.py
from django.core.management.base import BaseCommand, CommandError
from requests import RequestException

from xfeed.models import Tweet
from xfeed.services import fetch_last_tweets, to_model_kwargs


class Command(BaseCommand):
    help = "Fetch recent posts for X accounts and store the new ones"

    def add_arguments(self, parser):
        parser.add_argument("usernames", nargs="+")
        parser.add_argument("--pages", type=int, default=1)

    def handle(self, *args, **opts):
        for user in opts["usernames"]:
            cursor, offered, inserted = "", 0, 0
            for _ in range(opts["pages"]):
                try:
                    tweets, more, cursor = fetch_last_tweets(user, cursor)
                except RequestException as exc:
                    raise CommandError(f"{user}: {exc}")
                before = Tweet.objects.count()
                Tweet.objects.bulk_create(
                    [Tweet(**to_model_kwargs(t)) for t in tweets],
                    ignore_conflicts=True,  # the unique tweet_id drops repeats
                )
                offered += len(tweets)
                inserted += Tweet.objects.count() - before
                if not more or not cursor:
                    break
            self.stdout.write(self.style.SUCCESS(f"{user}: {inserted} new, {offered - inserted} already stored"))
06 — Section

How often to poll, and what it costs

Organization accounts post slowly. Over the span each sample covered, the median account posted 0.65 times a day; @djangoproject posted 0.4 times a day with a median gap of 34.9 hours, and the busiest account in the set posted 15.53 times a day.

A timeline call returns up to 20 posts whether or not any are new, and reads are billed at 15 credits per tweet returned. A full page costs $0.003. Our second poll returned 135 posts and stored none: $0.02025 for zero new rows.

Polling plan, per accountCalls a monthCost a month
last_tweets every 15 min2,880up to $8.64
last_tweets hourly720up to $2.16
advanced_search with since_time: every 60 s, nothing new43,200$6.48 (the $0.00015 minimum each)
advanced_search with since_time: every 5 min, nothing new8,640$1.30

The pattern that scales: backfill once with last_tweets, then poll with one advanced_search for all accounts (from:a OR from:b since_time:<last seen unix>), store since_time from the newest created_at you hold, and keep the unique constraint as the safety net. One search covers many accounts, and an empty answer costs the minimum. We did not run the search path in this study (search had intermittent 503s that day); the costs in those two rows come from the published price rules, not from our run.

For comparison, the official X API lists $0.005 per post read on its pay-per-usage card (docs.x.com/x-api/getting-started/pricing), capped at 3 million post reads a month, with Enterprise above that. At $0.15 per 1,000 tweets that is about 33x cheaper per 1,000 tweets read here. See pricing for credits and plans.

Bar chart of posts per day for eight organization accounts on a log scale, each with the second poll returning a page and 0 new posts
Posts per day per account and what the second poll returned. Collected in 2026.
07 — Section

Step 5: views, templates and the cache

The view reads up to 200 rows with .only() so the large raw column is not loaded, and renders them in a plain loop. Use linebreaksbr for text, not |safe: tweet text is user content and Django's autoescaping is what keeps it from injecting HTML into your page.

We timed the view with Django's test client on the same machine, 50 requests after a warm-up. Uncached: a median 4.27 ms and 1 database query per request. With @cache_page(60): a median 0.08 ms and 0 queries on a cache hit. The absolute numbers are local and small; the useful part is that a cache hit never touches the database, so a traffic spike lands on the cache.

Cache in a second place too: around the API call itself. cache.get_or_set(key, callable, timeout) (signature from Django's cache docs) means a manual refresh, a retry or two workers starting at once buy the same page only once. The single-file example below does this with a 300-second timeout, which is also the default TIMEOUT of Django's cache backends.

If you want the post to look like a native tweet rather than your own markup, render X's embed for the stored url; the guide to embedding tweets on a website covers the options and their weight.

python
# xfeed/views.py
from django.shortcuts import render
from django.views.decorators.cache import cache_page

from .models import Tweet


@cache_page(60)
def feed(request):
    tweets = Tweet.objects.only("tweet_id", "author_username", "text", "created_at", "like_count", "url")[:200]
    return render(request, "xfeed/feed.html", {"tweets": tweets})

# xfeed/templates/xfeed/feed.html
# <ul>
# {% for t in tweets %}
#   <li><a href="{{ t.url }}">@{{ t.author_username }}</a> {{ t.created_at|date:"Y-m-d H:i" }}
#     <p>{{ t.text|linebreaksbr }}</p><small>{{ t.like_count }} likes</small></li>
# {% empty %}
#   <li>No posts yet.</li>
# {% endfor %}
# </ul>
08 — Section

Scheduling: cron, Celery beat, or a long-running loop

Cron or a systemd timer. The simplest option: run manage.py poll_x every 15 minutes. Each run is a fresh process, so a crash never leaves a stuck worker. This is what we recommend for a handful of accounts.

Celery beat. If your project already runs Celery, wrap the command body in a task and schedule it with beat. Make the task safe to run twice (the unique constraint already is) and give it a lock if runs can overlap.

A long-running loop. Only when you need near-real-time updates. Use a fixed interval, honor HTTP 429 by waiting before retrying, and remember that the account rate limit is 0.2 requests per second before the first payment and 20 after it.

If your pipeline grows past one Django app, an orchestrator helps; the Airflow guide shows the same fetch-store pattern as a DAG.

09 — Section

How we collected this

Question. What does a Django app have to store and deduplicate when it polls X organization timelines, and what does polling cost?

Accounts. @djangoproject, @ThePSF, @github, @vercel, @Docker, @PostgreSQL, @pypi, @realpython: organization accounts only.

Method. /twitter/user/last_tweets with default settings (replies excluded): three pages per account for the backfill, then one page per account 2.5 minutes later. 32 requests, 531 tweets returned, about $0.08 at 15 credits per tweet. Both passes were fed through a real Django 6.1.4 project (SQLite, Python 3.12.13) via its poll_x management command, which replayed the saved pages; the timing used Django's test client. Collected in 2026.

What it cannot show. Eight accounts, one moment: posting rates change, the second poll was minutes after the first, and accounts that post replies or threads behave differently. The view timings are from one laptop and SQLite. The advanced_search costs come from published prices, not from this run.

Privacy. Aggregates only; organization accounts only; no analysis of reposted or quoted authors.

python
"""Single-file Django demo: model, fetch, store with a unique id, render. Run: python app.py
Needs: pip install "django>=5.2" requests ; export TWITTERAPI_IO_KEY=..."""
import os
import sys
from datetime import datetime

import django
import requests
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="demo-only",
    INSTALLED_APPS=["django.contrib.contenttypes"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": "x_demo.sqlite3"}},
    CACHES={"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}},
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}],
    USE_TZ=True,
)
django.setup()

from django.core.cache import cache  # noqa: E402
from django.db import connection, models  # noqa: E402
from django.template import Context, Template  # noqa: E402

BASE = "https://api.twitterapi.io"
KEY = os.environ.get("TWITTERAPI_IO_KEY") or sys.exit("set TWITTERAPI_IO_KEY")
X_DATE = "%a %b %d %H:%M:%S %z %Y"


class Tweet(models.Model):
    tweet_id = models.CharField(max_length=20, unique=True)
    author_username = models.CharField(max_length=15)
    text = models.TextField()
    created_at = models.DateTimeField()
    like_count = models.PositiveIntegerField(default=0)
    view_count = models.PositiveBigIntegerField(null=True, blank=True)
    raw = models.JSONField()

    class Meta:
        app_label = "xdemo"


with connection.schema_editor() as editor:
    if Tweet._meta.db_table not in connection.introspection.table_names():
        editor.create_model(Tweet)


def fetch_user_tweets(username, pages=2):
    """Follow has_next_page / next_cursor; 15 credits per tweet returned."""
    cursor, out = "", []
    for _ in range(pages):
        r = requests.get(
            f"{BASE}/twitter/user/last_tweets",
            headers={"X-API-Key": KEY},
            params={"userName": username, "cursor": cursor},
            timeout=30,
        )
        r.raise_for_status()
        body = r.json()
        if body.get("status") == "error":
            sys.exit(body.get("msg"))
        out += (body.get("data") or {}).get("tweets") or []
        cursor = body.get("next_cursor", "")
        if not body.get("has_next_page") or not cursor:
            break
    return out


def store(tweets):
    before = Tweet.objects.count()
    Tweet.objects.bulk_create(
        [
            Tweet(
                tweet_id=t["id"],
                author_username=(t.get("author") or {}).get("userName", ""),
                text=t.get("text") or "",
                created_at=datetime.strptime(t["createdAt"], X_DATE),
                like_count=t.get("likeCount") or 0,
                view_count=t.get("viewCount"),
                raw=t,
            )
            for t in tweets
        ],
        ignore_conflicts=True,
    )
    return Tweet.objects.count() - before


if __name__ == "__main__":
    username = sys.argv[1] if len(sys.argv) > 1 else "djangoproject"
    # cache the API answer for 5 minutes so a reload does not buy the same page twice
    tweets = cache.get_or_set(f"x:last:{username}", lambda: fetch_user_tweets(username), 300)
    new = store(tweets)
    print(f"fetched {len(tweets)}, stored {new} new, {len(tweets) - new} already in the table")
    html = Template(
        "{% for t in tweets %}@{{ t.author_username }} {{ t.created_at|date:'Y-m-d' }}: "
        "{{ t.text|truncatechars:80 }}\n{% endfor %}"
    ).render(Context({"tweets": Tweet.objects.order_by("-created_at")[:5]}))
    print(html)

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

Is there a Django package for the Twitter API?

You do not need one. The integration is a few dozen lines: a service function that calls the API with requests, a model with a unique tweet_id, and a management command. If you do pick a third-party package, check its last release date and which endpoints it targets before you depend on it.

Should I call the Twitter API inside a Django view?

No. A view that calls the API is as slow as the API, costs money per page view and fails when the network does. Fetch on a schedule with a management command, store in a model, and have views read the database, cached with cache_page.

How do I avoid duplicate tweets in my Django database?

Put unique=True on tweet_id and insert with bulk_create(objs, ignore_conflicts=True). In our run the second poll offered 135 posts and the constraint skipped all of them; even the backfill contained 3 repeats across pages. Note that bulk_create does not call save() or send signals.

What field type should hold the tweet text?

TextField. In our sample 22.4% of posts were longer than 280 characters and the longest was 674, so CharField(max_length=280) would reject real posts on databases that enforce length.

How often should a Django app poll X?

Match the accounts. The median organization account in our sample posted 0.65 times a day, so every 15 to 60 minutes is plenty. For many accounts, one advanced_search with from:a OR from:b since_time:<unix> per run is cheaper than one timeline call per account, because an empty search costs the $0.00015 minimum.

Do I need an X developer account or OAuth for this?

Not for reading public data through TwitterAPI.io: you send an API key in the X-API-Key header and no X account is needed. New accounts get free starter credits (no card, one per person or network, expiring after 31 days); see the pricing page for the amount.

Can my Django app post tweets too?

Yes, through an authenticated session: one /twitter/user_login_v2 login ($0.10, with a proxy you supply) returns login_cookies, then /twitter/create_tweet_v2 costs 60 credits ($0.0006) per successful call; calls that return status: error are not charged. The call acts as that account, so X can rate-limit, lock or suspend it; keep a normal human pace, and expect the session to need re-login at times.

Which Django version should I use?

Per djangoproject.com, 5.2 is the current LTS with extended support until April 2028, and 6.1 is the latest release. 6.x needs Python 3.12 or newer. The code on this page ran on 6.1 and uses nothing 5.2 lacks.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.