简体   繁体   中英

ForeignKey to specific queryset django

Is there a way to refer to specific object of Model ? Suppose I have some models like below:

# models.py

class VehicleCategoryCode(models.Model):
    category = models.CharField(max_length=5)
    name = models.CharField(max_length=20)

class Code(models.Model):
    category = models.ForeignKey(VehicleCategoryCode, on_delete=models.CASCADE)
    index = models.CharField(max_length=4, blank=True)
    label = models.CharField(max_length=50)
    order = models.CharField(max_length=20, blank=True)
    is_active = models.BooleanField(default=True)

# pay attention to the Model
class Vehicle(models.Model):
    label = models.CharField(max_length=80)
    model = models.CharField(max_length=30)

Currently Vehicle is not linked to any model.

Now Code model is ForeignKey to VehicleCategoryCode , which has two objects. In the VehicleCategoryCode the first object label (for convenience sake) will be referenced by Vehicle.label, and the second object model (once again for convenience) will be referenced by Vehicle.model. So each field in Vehicle can refer to the same model, but different objects.

So basically I'm wondering if something like the pseudo code below can be achieved anyhow.

class Vehicle(models.Model):
    label = models.ForeignKey(VehicleCategoryCode__name='label', on_delete=models.CASCADE)
    model = models.ForeignKey(VehicleCategoryCOde__name='model', on_delete=models.CASCADE)

Any suggestion or advice would be appreciated. Thank you.

You can make use of the limit_choices_to=… parameter [Django-doc] :

Vehicle(models.Model):
    label = models.ForeignKey(
        Code,
        ,
        on_delete=models.CASCADE
    )
    model = models.ForeignKey(
        Code,
        ,
        on_delete=models.CASCADE
    )

For ModelForm s and in the ModelAdmin it will limit the choices, note however that tese are not enforced by the database.

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