Django中的这些模型之间的关系 [英] Relationships among these models in Django

查看:80
本文介绍了Django中的这些模型之间的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个网站:


  • 有一组10张卡


  • 每个用户选择哪个卡是重要的,不重要的(来自同一组10张卡)

  • 他的选择被保存并链接到他的帐户。

  • there is a set of 10 Cards
  • on each Card, there are Important/Not_Important/Unknown attributes
  • each User chooses which card are important and not important (from the same set of 10 Cards)
  • his choices are saved and linked to his account.

我已经提出了这样的模式:

I have come up with models like these:


  1. 用户:我使用 django.contrib.auth.models.User

  2. 卡:

  1. User: I use django.contrib.auth.models.User
  2. Card:

class Card(models.Model):
    is_important = models.NullBooleanField(default=None)


  • CardSet:

  • CardSet:

    class CardSet(models.Model):
    
        cards = models.ManyToManyField(Card)
    
        user = models.ForeignKey(User,related_name='card_set')
    


  • 对我而言,这个数据库的关系是显而易见的,因为我没有知道如何检索用户实例决定重要/不重要/未知的卡片列表。但是,我不知道如何把它们放在正确的关系中。

    It is obvious to me this database relationship has something wrong because, I don't know how to retrieve a list of cards that an instance of User has decided to be important/not important/unknown. However, I don't know how to put them in right relationship.

    推荐答案

    我想我已经找到了我的问题的解决方案:
    模型将如下所示:

    I guess I have found the solution to my question: The models would be like this :

    class Card(models.Model):
        card_number = models.IntegerField(unique=True)
        content = models.TextField(null=False)
    
    class Choice(models.Model):
        user = models.ForeignKey(User)
        card = models.ForeignKey(Card)
        is_important = models.NullBooleanField(default=None)
    
        class Meta:
            unique_together = ('user','card')
    

    答案的关键是使用 unique_together 元选项。

    The key to the answer is to use unique_together Meta option.

    请查看我的解决方案,如果您有更好的解决方案或任何其他解决方案,请随时提出建议。我可以从你那里学到很多东西。

    Please review my solution and if you have a better solution or any alternative solution, please feel free to suggest. I can learn a lot from yours.

    谢谢!

    这篇关于Django中的这些模型之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆