🧑💻 Interacting with Django ORM
Sat 4 Jun, 2022
from django.db import models
#from django.forms import IntegerField
# Create your models here.
# Generally, each model maps to a single database table.
"The player account"
class Account(models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=20, unique=True)
planet = models.CharField(max_length=20, unique=True)
ore = models.PositiveIntegerField(default=500)
gas = models.PositiveIntegerField(default=500)
asteroids = models.PositiveIntegerField(default=10)
population = models.PositiveIntegerField(default=1)
def title(self):
"Returns the title of the player"
return '{} of {}'.format(self.name, self.planet)
def __str__(self):
"Sets the ORM refernce of the object as the title()"
return self.title()
------------------------------------------------------------------------
Console:
(ve) jamie@moon:~/websites/game.jcaston.uk$ python manage.py shell
Python 3.8.10 (default, Mar 15 2022, 12:22:08)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from apps.spacegame.models import Account
>>> account = Account()
>>> account.name = 'Kirsty'
>>> account.planet = 'Brighton'
>>> account.save()
>>> Account.objects.all()
<QuerySet [<Account: Jamie of Skyhouse>, <Account: Kirsty of Brighton>]>
>>>
You have now interacted with the project database via the Django ORM and have added two accounts!