Using the Django Model under the Python Shell interpreter

Source: Internet
Author: User

Sys.path.append (' E:/projects/djangoprojects/myfirstsite ')

Os.environ.setdefault (' Django_settings_module ', ' myfirstsite.settings ')

From books.models Import *

Print (Author.objects.all ())

as follows (Http://stackoverflow.com/questions/8047204/django-script-to-access-model-objects-without-using-manage-py-shell):

Since Django 1.4 You should avoid using setup_environ(settings) (post by Melug) because it is deprecated. Use the following instead and you'll be able to access your model

import osos.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")# your imports, e.g. Django modelsfrom your_project_name.models import Location# From now onwards start your script..

Example to access and modify your model:

if __name__ == ‘__main__‘:        # e.g. add a new location    l = Location()    l.name = ‘Berlin‘    l.save()    # this is an example to access your model    locations = Location.objects.all()    print locations    # e.g. delete the location    berlin = Location.objects.filter(name=‘Berlin‘)    print berlin    berlin.delete()

Example Model:

class Location(models.Model):    name = models.CharField(max_length=100)

Using the Django Model under the Python Shell interpreter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.