Django中的选择性外键使用(可能带有limit_choices_to参数?)

时间:2023-01-14 19:36:14

I'm a newbie to Django who just went through the making first app tutorials. I have a question regarding foreignkey

我是Django的新手,刚刚完成了制作第一个应用程序教程。我有一个关于外键的问题

In models.py I have two classes called Post and GroupMeeting. In groupmeetings, there is a foreignkey linking to Post class. Now, I want GroupMeetings to have only the Post items where category = 0

在models.py中,我有两个名为Post和GroupMeeting的类。在groupmeetings中,有一个foreignkey链接到Post类。现在,我希望GroupMeetings只包含category = 0的Post项

In My Implementation, I call all the Post Items. Is there a way to filter it using limit_choices_to argument or something else? (I don't quite understand how limit_choices_to argument works...)

在我的实现中,我调用所有的帖子项目。有没有办法使用limit_choices_to参数或其他东西过滤它? (我不太明白limit_choices_to参数是如何工作的......)

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)

1 个解决方案

#1


1  

If you want to limit choices for a foreign key, here is how to do it:

如果要限制外键的选择,请按以下步骤操作:

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})

Pretty simple as long as the choices are not context dependent.

只要选择不依赖于上下文,那就非常简单。

#1


1  

If you want to limit choices for a foreign key, here is how to do it:

如果要限制外键的选择,请按以下步骤操作:

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})

Pretty simple as long as the choices are not context dependent.

只要选择不依赖于上下文,那就非常简单。