choice of web-framework

justin walters walters.justin01 at gmail.com
Tue Oct 24 11:30:56 EDT 2017


On Tue, Oct 24, 2017 at 4:14 AM, Chris Angelico <rosuav at gmail.com> wrote:

>
> (There are other ORMs than SQLAlchemy, of course; I can't recall the
> exact syntax for Django's off the top of my head, but it's going to be
> broadly similar to this.)
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>


I can help with that:

## Defining a model:

class Thing(models.Model):
    """
        This is the "schema" for the `thing` table. The pk field is created
        automatically and is called `id` by default. This table with have
        four columns: `id`, `foo`, `baz`, and `score`.
    """
    foo = models.Charfield(
        max_length=140,
        blank=False
    )
    baz = models.CharField(
        max_length=140,
        blank=True
    )
    score = models.IntegerField()

## Create an object:

new_thing = Thing.objects.create(foo="bar", baz="foo")

## Get a list of objects:

Thing.objects.all()

## Filter a list of objects:

Thing.objects.filter(foo="bar")

## Modify an object:

thing = Thing.objects.get(id=1)
thing.foo = "baz"
thing.save()

## Perform an aggregation:

data = Thing.objects.aggregate(avg=Avg("score"))
print(data)
>>> {"avg": 50}

## Django basic view(called controllers in other frameworks normally) and
template:

def person_list(request):
    """
        Get a collection of `User` objects from the database.
    """
    people = User.objects.filter(is_active=True).order_by("date_joined")
    return render(
        request,
        "person/list.html",
        context={"people": people}
    )


Then, in `templates/person/list.html`:

{% extends 'base.html' %}

{% block content %}
<div>
    {% for person in people %}
        <div>
            <h3>{{person.first_name}} {{person.last_name}}</h3>
        </div>
    {% endfor %}
</div>
{% endblock %}


Alternatives to Django's ORM and SQLAlchemy include but are not limited to:

- Peewee: https://github.com/coleifer/peewee
- PonyORM: https://ponyorm.com/



More information about the Python-list mailing list