简体   繁体   中英

Selective Foreign Key Usage in Django (maybe with limit_choices_to argument?)

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

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

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM