如何将字段从一个模型链接到另一模型的特定字段

时间:2019-02-27 23:30:29

标签: django

所以我有一个平台类,可以在其中设置所有平台

library / models.py

from django.db import models
from django.utils import timezone

# Create your models here.
class Platform(models.Model):
    platform = models.CharField(max_length=20)

    def __str__(self):
        return self.platform

class Game(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    cover = models.ImageField()
    cover_display = models.ImageField(default='default.png')
    developer = models.CharField(max_length=100)
    twitter = models.CharField(max_length=50, default='')
    reddit = models.CharField(max_length=50, default='')
    platform = models.ManyToManyField(Platform)

    def __str__(self):
        return self.title

然后我有一个模型类,可以在其中设置该游戏的平台

,每个游戏都有自己的帖子。如何在发布模型中设置平台字段以从游戏模型继承平台。我这样做是为了按游戏特定平台对帖子进行排序。

main / models.py

from django.db import models
from library.models import Game, Platform
from users.models import User
from django.utils import timezone
from django.urls import reverse
from vote.models import VoteModel

# Create your models here.
class Post(models.Model):
    article_title = models.CharField(max_length=100)
    content = models.TextField()
    date_published = models.DateTimeField(db_index=True, default=timezone.now)
    game = models.ForeignKey(Game, on_delete=models.CASCADE)
    article_image = models.ImageField(default='/media/default.png', upload_to='article_pics')
    platform = models.ForeignKey(Game, related_name='platform')

    def __str__(self):
        return self.article_title

    class Meta:
        ordering = ["-date_published"]


    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

1 个答案:

答案 0 :(得分:0)

在提出解决方案之前,您需要了解重复的字段表示您的模型未标准化。我建议您从Post中删除现场平台,因此您的新模型如下:

class Post(models.Model):
    article_title = models.CharField(max_length=100)
    content = models.TextField()
    date_published = models.DateTimeField(db_index=True, default=timezone.now)
    game = models.ForeignKey(Game, on_delete=models.CASCADE)
    article_image = models.ImageField(default='/media/default.png', upload_to='article_pics')

现在要基于平台对Post进行排序,您只需要使用以下ORM查询:

posts_by_platforms = Post.objects.all().order_by(game__platform)

或者如果您想按平台和日期订购它们,可以使用:

posts_by_platforms = Post.objects.all().order_by(-date_published, game__platform)