简体   繁体   English

基于另一个模型的Django模型选择

[英]Django Model choices based off another model

Sorry if this is confusing, I'm still a bit green with Django.对不起,如果这令人困惑,我对 Django 仍然有点陌生。 So basically I have two models and I want a selection from one to have all the choices from another model.所以基本上我有两个模型,我希望从一个模型中进行选择,以获得另一个模型的所有选择。 So basically:所以基本上:

class Show(models.Model):

venue = models.CharField(max_length=100, choices = VENUE NAME)

class Venues(models.Model):
Name = models.CharField(max_length=100)

Essentially I want the venue to have a list of the venue names that were input into that model.本质上,我希望场地有一个输入到该模型中的场地名称列表。 Is this possible?这可能吗?

In your case you should use many-to-one ForeignKey在您的情况下,您应该使用多对一的外键

It give you access to Venues object from your Show object and it simple to add this to your model.它使您可以从Show对象访问Venues对象,并且很容易将其添加到您的模型中。

class Show(models.Model):
    venue = models.ForeignKey('Venues', on_delete=models.CASCADE)

class Venues(models.Model):
    name = models.CharField(max_length=100)

To get your choices you can use:要获得您的选择,您可以使用:

Venues.objects.all()

And then the only thing you need is add object or ID to your Show object and save.然后您唯一需要的是将对象或 ID 添加到您的Show对象并保存。

Choices are good too but not in this case.选择也很好,但在这种情况下不是。 For example when you need some const and give user choices like this:例如,当您需要一些常量并为用户提供如下选择时:

class Show(models.Model):
    VENUES_CHOICES = (
        (RESTAURANT, 'restaurant'),
        (PUB, 'pub'),
    )

    venues = models.IntegerField(choices=VENUES_CHOICES, default=RESTAURANT)

Its great to use it in order status in my opinion.在我看来,在订单状态下使用它很棒。

add a str def like this in the Venues model will do在 Venues 模型中添加这样的str def 就可以了

def __str__ (self):
    return self.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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