使用其他应用程序模型作为外键

时间:2017-10-07 19:33:57

标签: django postgresql

我得到的错误。

function prime(num){
  if (num == 0){
        return 0;
    }   
 return num%prime(num-1)  
}

console.log(prime(6));

我有一个用于创建名为home的匹配的应用。它有一个匹配模型。

home.models.py

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/create/

Django Version: 1.11.1
Python Version: 3.5.3
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'whitenoise.runserver_nostatic',
 'django.contrib.staticfiles',
 'widget_tweaks',
 'home',
 'soccer']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'whitenoise.middleware.WhiteNoiseMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:djangosite\lib\site-packages\django\db\backends\base\base.py" in _commit
  236.                 return self.connection.commit()

The above exception (insert or update on table "soccer_game" violates foreign key constraint "soccer_game_match_id_7834e80f_fk_soccer_match_id"
DETAIL:  Key (match_id)=(7) is not present in table "soccer_match".
) was the direct cause of the following exception:

File "C:djangosite\lib\site-packages\django\core\handlers\exception.py" in inner
  41.             response = get_response(request)

File "C:djangosite\lib\site-packages\django\core\handlers\base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "C:djangosite\lib\site-packages\django\core\handlers\base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:djangosite\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "C:djangosite\sports\home\views.py" in create
  24.               g = Game.objects.create(match=m, player=p)

File "C:djangosite\lib\site-packages\django\db\models\manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "C:djangosite\lib\site-packages\django\db\models\query.py" in create
  394.         obj.save(force_insert=True, using=self.db)

File "C:djangosite\lib\site-packages\django\db\models\base.py" in save
  806.                        force_update=force_update, update_fields=update_fields)

File "C:djangosite\lib\site-packages\django\db\models\base.py" in save_base
  836.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "C:djangosite\lib\site-packages\django\db\transaction.py" in __exit__
  223.                         connection.commit()

File "C:djangosite\lib\site-packages\django\db\backends\base\base.py" in commit
  262.         self._commit()

File "C:djangosite\lib\site-packages\django\db\backends\base\base.py" in _commit
  236.                 return self.connection.commit()

File "C:djangosite\lib\site-packages\django\db\utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "C:djangosite\lib\site-packages\django\utils\six.py" in reraise
  685.             raise value.with_traceback(tb)

File "C:djangosite\lib\site-packages\django\db\backends\base\base.py" in _commit
  236.                 return self.connection.commit()

Exception Type: IntegrityError at /create/
Exception Value: insert or update on table "soccer_game" violates foreign key constraint "soccer_game_match_id_7834e80f_fk_soccer_match_id"
DETAIL:  Key (match_id)=(7) is not present in table "soccer_match". 

GAMES选项是所有其他运动/游戏应用的列表。其中一个是足球,有这些模型。

soccer.models.py

from django.db import models

class Match(models.Model):
    pick = models.CharField(max_length=30, choices=GAMES)
    name = models.CharField(max_length=30)
    created = models.DateTimeField(auto_now_add=True)
    players = models.IntegerField(choices=NUM_PLAYERS)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "matches"

然后在家庭应用程序中创建匹配的视图。

home.views.py

from django.conf import settings
from django.db import models
from home.models import Match

class Player(models.Model):
    name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    number = models.IntegerField(default=0)
    score = models.IntegerField(default=0)

    def __str__(self):
        return self.name.username


class Settings(models.Model):
    match = models.ForeignKey('home.Match')
    time = models.IntegerField(default=0)

    class Meta:
        verbose_name_plural = 'settings'

    def __str__(self):
        return self.match.name

class Game(models.Model):
    match = models.ForeignKey('home.Match')
    player = models.ForeignKey(Player)

    def __str__(self):
        return self.match.name

我在尝试将其用作外键之前创建并保存匹配,因此我不确定导致错误的原因。

0 个答案:

没有答案