如何加入这些Django模型?

时间:2019-05-13 05:37:41

标签: django django-models

我应该如何加入这些Django模型,以获取参与已登录用户挑战的所有Player模型(请参阅views.py中的名为Challenges_participants的变量?我没有想出如何使用Django模型有效实现此问题的解决方案。非常感谢!

示例数据: 让我们假设John已登录。正如我们在PlayerChallenge模型中所看到的,他是挑战1和2的一部分。我要做的是获取所有属于挑战1(Roger是本例)和第二个挑战的玩家对象。列出挑战2的所有玩家对象(在此示例中为Roger和Claude)。

玩家模型

╔═══════════╦═════════╦════════════════╗
║ user_name ║ user_id ║ wallet_balance ║
╠═══════════╬═════════╬════════════════╣
║ John      ║     123 ║             20 ║
║ Roger     ║     231 ║             15 ║
║ Claude    ║     582 ║             10 ║
╚═══════════╩═════════╩════════════════╝

挑战模型

╔════╦═════════╦══════╦════════╦═══════════════════╦══════════╦═══════════════════╦═══════════════╗
║ id ║ status  ║ type ║ amount ║ created_timestamp ║ duration ║ started_timestamp ║ end_timestamp ║
╠════╬═════════╬══════╬════════╬═══════════════════╬══════════╬═══════════════════╬═══════════════╣
║  1 ║ active  ║    1 ║     20 ║ TimeStamp         ║ 02:00:00 ║ TimeStamp         ║ TimeStamp     ║
║  2 ║ waiting ║    2 ║     30 ║ TimeStamp         ║ 04:00:00 ║ TimeStamp         ║ TimeStamp     ║
║  3 ║ waiting ║    1 ║     35 ║ TimeStamp         ║ 07:00:00 ║ TimeStamp         ║ TimeStamp     ║
╚════╩═════════╩══════╩════════╩═══════════════════╩══════════╩═══════════════════╩═══════════════╝

PlayerChallenge模型

╔════╦════════╦═══════════╦════════════════════╗
║ id ║ player ║ challenge ║ accepted_timestamp ║
╠════╬════════╬═══════════╬════════════════════╣
║  1 ║ John   ║         1 ║ TimeStamp          ║
║  2 ║ Roger  ║         1 ║ TimeStamp          ║
║  3 ║ Roger  ║         2 ║ TimeStamp          ║
║  4 ║ Claude ║         2 ║ TimeStamp          ║
║  5 ║ John   ║         2 ║ TimeStamp          ║
╚════╩════════╩═══════════╩════════════════════╝

代码:

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

# Create your models here.

class Player(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    #additional fields
    userid = models.CharField(max_length=256)
    wallet_balance = models.IntegerField(default=0)
    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Player.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.player.save()


class Challenge(models.Model):
    id = models.IntegerField(primary_key=True, unique=True)
    status = models.CharField(max_length=20)
    type = models.CharField(max_length=20)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    created_timestamp = models.DateTimeField()
    duration = models.DurationField()
    started_timestamp = models.DateTimeField(null=True, blank=True)
    end_timestamp = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return str(self.id)

class PlayerChallenge(models.Model):
    user_challenge_id = models.IntegerField(primary_key=True, unique=True)
    player = models.ForeignKey(Player, on_delete=models.CASCADE)
    challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE)
    accepted_timestamp = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return str(self.user_challenge_id) + " (Player: " + str(self.player.user.username) + ", Challenge: " + str(self.challenge.id) + ")"

views.py

from django.shortcuts import render
from django.http import HttpResponse

from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User

from challengeview.models import Player,Challenge,PlayerChallenge

@login_required
def index(request):

    challenges = Challenge.objects.filter(playerchallenge__player = request.user.player)
    challenges_participants = Player.objects.filter(playerchallenge__challenge = challenges)

    my_dict = {
     'challenges_participants' : challenges_participants,
     'challenges' : challenges,

    }
    return render(request, "challengeview/index.html", context=my_dict)

非常感谢您的支持!

1 个答案:

答案 0 :(得分:0)

在Django中,您不能像在简单的 SQL 表中那样对关系建模。共有3种强大的关系类型OnetoOne, ForeignKey, ManytoMany。     从django.utils导入时区

class Player(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    #additional fields
    userid = models.CharField(max_length=256)
    wallet_balance = models.IntegerField(default=0)
    challenges = models.ManyToMany('Challenge') #a challenge can be belonged to many players in this case
    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Player.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.player.save()


class Challenge(models.Model):
    status = models.CharField(max_length=20)
    type = models.CharField(max_length=20)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    duration = models.DurationField()
    started_timestamp = models.DateTimeField(null=True, blank=True)
    end_timestamp = models.DateTimeField(null=True, blank=True)
    created_timestamp = models.DateTimeField()

    def __str__(self):
        return str(self.id)


class PlayerActivity(models.Model):
    challenge = models.ForeingKey(on_delete=models.SET_NULL,
                                   null=True,
                                 related_name='activity_challenge')
    created_by = models.ForeignKey(Player,
                                   on_delete=models.SET_NULL,
                                   null=True,
                                 related_name='activity_created_by')

    created_at = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return str(self.user_challenge_id) + " (Player: " + str(self.player.user.username) + ", Challenge: " + str(self.challenge.id) + ")"

如果一个挑战只能属于一个玩家,而一个玩家却可以有很多挑战,那么外键。如果一个玩家可以遇到很多挑战,而一个挑战可以属于许多玩家,那么 ManyToMany

使用查询时,您应该始终想到发送到后端的请求。您可以使用select_related来最小化请求。

all_challenges = Challenge.objects.all()
logged_user_challenges = Player.objects.filter(user=request.user,challenges__in=all_challenges)
others_same_challenges = Player.objects.filter(challenges=logged_user_challenges.challenges)

OR

logged_user_challenges = PlayerActivity.objects.filter(user=request.user).latest('created_at')

但是您将与其他人有问题_...您将需要一个循环来获取全部信息,这是不建议的。

注意:您必须操纵视图中的数据保存。