社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

我怎样才能像manytomanyfield一样在django admin下拉菜单中选择foreignkey数据?

moongdal • 4 年前 • 1954 次点击  

模型。py

from django.db import models

class Images(models.Model):

    def upload_path(instance, filename):
        return '/images/'.join([filename])

    image = models.ImageField(upload_to=upload_path, blank=True, null=True)
    logits = models.BinaryField()
    #customer = models.ForeignKey(Customer ,on_delete=models.DO_NOTHING, default=None)

class Customer(models.Model):
    customer_id = models.BigIntegerField(unique=True)
    first_name = models.CharField(max_length=300)
    last_name = models.CharField(max_length=300)
    images = models.ForeignKey(Images ,on_delete=models.DO_NOTHING, default=None)
    def __str__(self):
        return str(self.customer_id)

我的问题是,我希望能够将多个图像分配给单个用户,这应该是可能的,因为ForeignKey,但我似乎无法让它像那样工作。

我想要多选字段,就像在许多字段中一样,但在外键字段中。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/133811
文章 [ 1 ]  |  最新文章 4 年前
Willem Van Onsem
Reply   •   1 楼
Willem Van Onsem    4 年前

我的问题是[我]希望能够将多个图像分配给[一个]单个用户,这应该是可能的,因为 ForeignKey 但(我)似乎无法让它像那样工作。

不 :A 外国钥匙 是一个 多对一 关系:意思是 许多的 Customer s可以指一个,可能是同一个,单 Images .如果你想使用多个 Image 那么你需要写下 外国钥匙 相反的方向,所以:

from django.db import models

class Image(models.Model):

    def upload_path(instance, filename):
        return f'/images/{filename}'

    image = models.ImageField(upload_to=upload_path, blank=True, null=True)
    logits = models.BinaryField()
    customer = models.ForeignKey(
        'Customer',
        on_delete=models.SET_NULL,
        null=True,
        related_name='images'
    )

class Customer(models.Model):
    customer_id = models.BigIntegerField(unique=True)
    first_name = models.CharField(max_length=300)
    last_name = models.CharField(max_length=300)
    
    def __str__(self):
        return f'{self.customer_id}'