ForeignKey to abstract class (generic relations)

后端 未结 4 1354
长情又很酷
长情又很酷 2020-12-24 04:41

I\'m building a personal project with Django, to train myself (because I love Django, but I miss skills). I have the basic requirements, I know Python, I carefully read the

4条回答
  •  失恋的感觉
    2020-12-24 05:16

    For a start, use Django's multi-table inheritance, rather than the abstract model you have currently.

    Your code would then become:

    from django.db import models
    
    class Service(models.Model):
        port = models.PositiveIntegerField()
    
    class SSHService(Service):
        username = models.CharField(max_length=64)
        pkey = models.TextField()   
    
    class TelnetService(Service):
        username = models.CharField(max_length=64)
        password = models.CharField(max_length=64)
    
    class GenericTcpService(Service):
        pass
    
    class GenericUDPService(Service):
        pass
    
    class Node(models.Model):
        name = models.CharField(max_length=64)
        # various fields                                                                                                                                
        services = models.ManyToManyField(Service)
    

    On the database level, this will create a 'service' table, the rows of which will be linked via one to one relationships with separate tables for each child service.

    The only difficulty with this approach is that when you do something like the following:

    node = Node.objects.get(pk=node_id)
    
    for service in node.services.all():
        # Do something with the service
    

    The 'service' objects you access in the loop will be of the parent type. If you know what child type these will have beforehand, you can just access the child class in the following way:

    from django.core.exceptions import ObjectDoesNotExist
    
    try:
        telnet_service = service.telnetservice
    except (AttributeError, ObjectDoesNotExist):
        # You chose the wrong child type!
        telnet_service = None
    

    If you don't know the child type beforehand, it gets a bit trickier. There are a few hacky/messy solutions, including a 'serviceType' field on the parent model, but a better way, as Joe J mentioned, is to use a 'subclassing queryset'. The InheritanceManager class from django-model-utils is probably the easiest to use. Read the documentation for it here, it's a really nice little bit of code.

提交回复
热议问题