Update multiple object attributes at once

Calculus

I have such a data model with topic and entry:

class Topic(models.Model):
    """A topic the user is learning about."""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User)

    def __str__(self):
        """Return a string representation of the model."""
        return self.text

class Entry(models.Model):
    """Something specific learned about a topic"""
    topic = models.ForeignKey(Topic)
    title = models.CharField(max_length=200)
    text = models.TextField()
    tags = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        """Return string representation of the model"""
        return self.text[:50] + "..."

I intend to retrieve the entries whose topic is questions and title starts with numerals,
then change the unqualified titles to
the qualified title which I set is the first line retrieved from entry's text.

entries = (Entry.objects
                .filter(topic__text="Questions")
                .filter(title__regex=r"^\d+"))

In[63]: [entry.title for entry in entries]
Out[63]: ['1', '1', '1', '1', '1']

Replace the integer with the first line of entry's text as the title:

def first_line(text): return re.search(r".+", text).group()

for entry in entries:
    new_title = first_line(entry.text)
    setattr(entry, 'title', new_title)
    entry.save()

I am novice of Django, and wondering:

  1. If "regex" is a best solution to filter titles startswith a numerical?
  2. entry.save() is implemented multiple times, could all the changes be saved in one go?
  3. Could such operations be handle on database level?
dorintufar

did you tried to operate with transactions?

def first_line(text): 
    return re.search(r".+", text).group()

@transaction.commit_manually
def manual_transaction():
    entries = Entry.objects
            .filter(topic__text="Questions")
            .filter(title__regex=r"^\d+")
    for record in entries:
        record.title = first_line(record.text)
        record.save()
    transaction.commit()

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Dynamically update attributes of an object that depend on the state of other attributes of same object

分類Dev

Entity Framework 5 Update works only once per object / row

分類Dev

How to use multiple ColumnDataSource and update all of them at once?

分類Dev

ComponentDidUpdate firing multiple time instead of once per update

分類Dev

Flot Chart - Graphic data as an object array with multiple attributes

分類Dev

Escape all attributes of an object

分類Dev

Giving attributes to an object in Python

分類Dev

Attributes to multiple fields

分類Dev

Deleting multiple mails at once

分類Dev

How update multiply descriptorSets at once

分類Dev

angularJS pass object attributes to modal

分類Dev

$resource returns Object with numeric attributes

分類Dev

PowerShell methods with multiple custom attributes

分類Dev

Create a list from multiple attributes

分類Dev

Add multiple attributes to a child in SimpleXMLElement

分類Dev

Rails Mongoid - Search on multiple attributes

分類Dev

Multiple data attributes to array with jQuery

分類Dev

Multiple data attributes to array with jQuery

分類Dev

Execute multiple queries at once in Mongoose

分類Dev

Insert multiple records at once in Cassandra

分類Dev

Rails. Update model attributes on save

分類Dev

Get edited attributes in eloquent before update

分類Dev

Rails undefined method update_attributes

分類Dev

Setting object attributes in a loop results in all attributes having the same value

分類Dev

aws cli query multiple attributes when these attributes are on the same level

分類Dev

How to update a value in multiples collections at once in firestore?

分類Dev

Rename the dir once update is finished - perl

分類Dev

Rails:update_attributeとupdate_attributes

分類Dev

How to extract attributes values from svyciprop object?

Related 関連記事

  1. 1

    Dynamically update attributes of an object that depend on the state of other attributes of same object

  2. 2

    Entity Framework 5 Update works only once per object / row

  3. 3

    How to use multiple ColumnDataSource and update all of them at once?

  4. 4

    ComponentDidUpdate firing multiple time instead of once per update

  5. 5

    Flot Chart - Graphic data as an object array with multiple attributes

  6. 6

    Escape all attributes of an object

  7. 7

    Giving attributes to an object in Python

  8. 8

    Attributes to multiple fields

  9. 9

    Deleting multiple mails at once

  10. 10

    How update multiply descriptorSets at once

  11. 11

    angularJS pass object attributes to modal

  12. 12

    $resource returns Object with numeric attributes

  13. 13

    PowerShell methods with multiple custom attributes

  14. 14

    Create a list from multiple attributes

  15. 15

    Add multiple attributes to a child in SimpleXMLElement

  16. 16

    Rails Mongoid - Search on multiple attributes

  17. 17

    Multiple data attributes to array with jQuery

  18. 18

    Multiple data attributes to array with jQuery

  19. 19

    Execute multiple queries at once in Mongoose

  20. 20

    Insert multiple records at once in Cassandra

  21. 21

    Rails. Update model attributes on save

  22. 22

    Get edited attributes in eloquent before update

  23. 23

    Rails undefined method update_attributes

  24. 24

    Setting object attributes in a loop results in all attributes having the same value

  25. 25

    aws cli query multiple attributes when these attributes are on the same level

  26. 26

    How to update a value in multiples collections at once in firestore?

  27. 27

    Rename the dir once update is finished - perl

  28. 28

    Rails:update_attributeとupdate_attributes

  29. 29

    How to extract attributes values from svyciprop object?

ホットタグ

アーカイブ