Django中的选择性外键用法(可能有limit_choices_to argument?)

2024-10-01 15:30:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Django的新手,刚学习了制作第一个应用程序的教程。 我有一个关于外国钥匙的问题

在模型.py 我有两门课,叫Post和GroupMeeting。 在groupmeetings中,有一个foreignkey链接到Post-class。 现在,我希望GroupMeetings只在 类别=0

在我的实现中,我调用所有Post项。 有没有一种方法可以使用limit\u choices\u to argument或其他东西来过滤它? (我不太明白“限制选项”如何起作用…)

class Post(models.Model):
    date = models.DateTimeField()
    category = models.IntegerField()
    content = models.CharField(max_length=400)
    #writerId ...
    CATEGORY = (
        (0, 'MeetingPost'),
        (1, 'AnnounceBoard'),
        (2, 'FreeBoard'),
    )
    tag = models.ManyToManyField(PostTag)
    replies = models.ForeignKey(PostReply)

class GroupMeeting(models.Model):
    date = models.DateTimeField()
    placeGPS = models.FloatField()
    placeName = models.CharField(max_length=30)
    dateRepeat= models.ForeignKey(RepeatDays)
    post = models.ForeignKey(Post)

Tags: django应用程序datemodelmodels教程postlength
1条回答
网友
1楼 · 发布于 2024-10-01 15:30:49

如果要限制外键的选择,请执行以下操作:

class GroupMeeting(models.Model):
    date = models.DateTimeField()
    placeGPS = models.FloatField()
    placeName = models.CharField(max_length=30)
    dateRepeat= models.ForeignKey(RepeatDays)
    post = models.ForeignKey(Post, limit_choices_to = {'category': 0})

很简单,只要选择不依赖于上下文。在

相关问题 更多 >

    热门问题