Django / Model with ManytoManyField gives en entry by default

Issue

Models.py

class Scenes(models.Model):
    name = models.SlugField('Scene name', max_length=60,unique=True)
    description = models.TextField(blank=True)
    fileGltf = models.FileField(null=TRUE, blank=False, upload_to="3dfiles/")
    
    record_date = models.DateTimeField('Scene date')

    manager = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        blank=True,
        null=True,
        on_delete=models.SET_NULL)
  
    prev = models.ForeignKey(
        'self', 
        related_name='previous',
        blank=True,
        null=True,
        on_delete=models.SET_NULL)

    next = models.ManyToManyField(
        'self',
         blank=True, )

Views.py (extract)

    if form.is_valid():
        nextSceneSlug=form.cleaned_data.get('name')
        scenes=form.save(commit=False)
        scenes.manager = request.user
        scenes.record_date = now
        scenes.prev = ScenePrevious
        form.save()

When I record a new entry with the models.py, there is a default value for this next field/
(World is the scene origine) But when I add it with the admin panel, there is not.
How can I do it in my views.py so it leaves a blank field ?

enter image description here

Solution

It makes no sense to specify a prev and next if it means that if A is the prev of B, then B is a member of the next of A. You can define a simple ForeignKey:

class Scene(models.Model):
    name = models.SlugField('Scene name', max_length=60, unique=True)
    description = models.TextField(blank=True)
    file_gltf = models.FileField(null=TRUE, upload_to='3dfiles/')
    record_date = models.DateTimeField('Scene date')
    manager = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        blank=True,
        null=True,
        on_delete=models.SET_NULL
    )
    previous = models.ForeignKey(
        'self', 
        related_name='next',
        blank=True,
        null=True,
        on_delete=models.SET_NULL
    )

If you thus have for example scenes B and C that both have A as previous, then A.next.all() will return a QuerySet that contains B and C.


Note: normally a Django model is given a singular name, so Scene instead of Scenes.

Answered By – Willem Van Onsem

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published