将查询集结果插入ManytoManyfield [英] Insert queryset results into ManytoManyfield

查看:31
本文介绍了将查询集结果插入ManytoManyfield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个models.py文件,看起来像这样:

I have a models.py file that looks like this:

from django.db import models
from common.models import Record
from tinymce import models as tinymce_models

# Create your models here.
class Address(Record):
    def __unicode__(self):
        return unicode(self.ip)

    ip = models.IPAddressField(unique=True)
    notes = models.TextField(blank=True)

    class Meta:
        verbose_name_plural = "Addresses"

class Servers(models.Model):
    def __unicode__(self):
        return unicode(self.server_name)

    server_name = models.CharField(max_length=100)
    ip_address = models.ForeignKey(Address)
    secondary_ips = models.ManyToManyField(Address, verbose_name = 'Secondary IPs', blank=True, related_name='secondary_ips')

    class Meta:
        verbose_name_plural = "Servers"

我在系统中有IP和服务器的列表.我试图让ManytoManyField仅显示当前未与服务器关联的IP列表.

I have a list of IP's and Servers in the system. I am trying to have the ManytoManyField only display the list of IP's that are not currently associated with a server.

我有以下查询集:

inner_qs = Servers.objects.values_list('ip_address_id', flat=True)
entries = Address.objects.exclude(id__in=inner_qs)

它仅返回不在Server表中的IP地址.我不知道如何将这些结果合并到我的ManytoManyField中,以及将查询集放置在何处.我目前仅在进入django Shell时得到结果

It returns only the IP addresses that are not in the Server table. I do not know how to incorporate those results into my ManytoManyField and where I am supposed to place my queryset. I currently only get the results when I enter the django Shell

任何想法,

谢谢

推荐答案

您可以在此处使用此答案:

You can use this answer here: Filter ManyToMany box in Django Admin

简而言之,您需要创建一个扩展 django.forms.ModelForm 的自定义表单.在那里,在 __ init __ 方法中,将新选项放置到正确的小部件( secondary_ips ).最后,将 form = YourOwnForm 添加到您正在使用的 ServerAdmin 类中.

In short, you need to create a custom form that extends django.forms.ModelForm. There, in __init__-method, place new options to the right widget (secondary_ips). Finally, add form = YourOwnForm to the ServerAdmin class you are using.

我建议在 Servers -model中修改 related_names :

I suggest modifying related_names in the Servers-model:

class Servers(models.Model):
    # ...
    ip_address = models.ForeignKey(Address, related_name='server')
    secondary_ips = models.ManyToManyField(Address, verbose_name = 'Secondary IPs', \
        blank=True, related_name='servers_secondary')

然后,您可以使用一个不错的QuerySet:

Then, you can use a nice QuerySet:

allowed_addresses = Address.objects.filter(server=None)

辅助地址

当然,这只会过滤某些服务器中作为主IP的IP.如果您还想过滤掉作为其他服务器中secondary_ip的ip,那么事情会变得有些棘手:

Of course, this filters only the IPs that are as a primary IP in some server. If you want to filter out also the ips that are as a secondary_ip in some other server, things get a bit trickier:

您还需要在 servers_secondary = None 上进行过滤.但是您不能过滤掉为当前对象(在admin中编辑的服务器)选择的IP,否则这些选择的IP也将消失.

You need to filter also on servers_secondary=None. But you can't filter out the IPs selected for the current object (the server that is edited in the admin), or those selected IPs will disappear too.

使用 Q来完成此操作对象,然后从 kwargs 抓取当前选定的对象.您自定义窗体的 __ init __ -方法将如下所示:

Accomplish this using Q objects, and grab the currently selected object from kwargs. Your custom Form's __init__-method will then look something like this:

def __init__(self, *args, **kwargs):
    super(YourOwnForm, self).__init__(*args, **kwargs)
    instance = kwargs.get('instance')
    allowed_addresses = Address.objects \
        .filter(server=None) \
        .filter(Q(servers_secondary=None) | Q(servers_secondary=instance))
    choices = []
    for choice in allowed_addresses:
        choices.append((choice.id, choice.ip))
    w = self.fields['secondary_ips'].widget
    w.choices = choices

主地址下拉菜单

采用相同的方法,也可以过滤主IP地址下拉菜单中的项目.当然,必须注意不要从列表中删除所选的IP地址.

Folowing the same method, it is also possible to filter items in the primary IP address drop-down menu. Of course, care must be taken not to remove the selected IP address from the list.

这篇关于将查询集结果插入ManytoManyfield的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆